说明: SpringBoot2.x之后,原来的jedis被替换成了lettuce
jedis:采用的直连,多个县城操作的话,是不安全的,如果想要避免不安全的,使用jedis pool连接池!更像BIO模式。
lettuce:采用netty,实例可以在多个线程中进行共享,不存在线程不安全的情况!可以减少线程数据了,更像NIO模式。
源码分析:
@Bean
@ConditionalOnMissingBean(
name = {"redisTemplate"}
)
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate
- 导入依赖
org.springframework.boot spring-boot-starter-data-redis-reactive
- 配置连接
spring:
redis:
host: 192.168.1.166
port: 6379
- 测试!
package redisspringboot;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class RedisSpringbootApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
// redisTemplate
// opsForValue 操作字符串 类似于String
// opsForList 操作List 类似List
// 除了基本的操作,常用的基本方法可以直接redisTemplate操作,比如事务和基本的增删改查
// 获取reids的连接对象
RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
connection.flushDb();
redisTemplate.opsForValue().set("mykey","zhangdg");
System.out.println(redisTemplate.opsForValue().get("mykey"));
}
}



