SpringBoot整合Redis
SpringBoot操作数据:spring-data jpa jdbc mongodb redis !
SpringData也是和SpringBoot齐名的项目!
说明︰在SpringBoot2.x之后,原来使用的jedis被替换为了lettuce
jedis :采用的直连,多个线程操作的话,是不安全的,
如果想要避免不安全的,使用jedis pool连接池!更像BIO模式
lettuce :采用netty,实例可以再多个线程中进行共享,不存在线程不安全的情况!
可以减少线程数据了,更像NIO模式
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")//我们可以自己自定义一个redis来代替这个默认的
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
//默认的RedisTemplate没有过多的设置,redis对象都是需要序列化!
//两个泛型都是Object类型,我们后续使用需要强制转换<String,Object>
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
由于String类型是redis常用的类型,所以单独提出来了一个bean
@Bean
@ConditionalOnMissingBean
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
return new StringRedisTemplate(redisConnectionFactory);
}
整合测试
-
导入依赖
-
配置连接
-
#配置redis
spring.redis.host=192.168.1.1
spring.redis.post=6379
spring.redis.password=123456
4. 测试
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
//redisTemplate 操作不同的数据类型,api和我们的指令一样
//opsForValue 操作字符串,类似String
//opsForList 操作List,类似list
//opsForSet
//opsForHash
//opsForZSet
//opsForGeo
//opsForHyperLogLog
//除了进本操作,我们常用的方法都可以直接通过redisTemplate操作,
// 比如事务,和基本的CRUD
//获取redis的连接对象
//RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
//connection.flushDb();
//connection.flushAll();
redisTemplate.opsForValue().set("key1","hello");
redisTemplate.opsForValue().set("key2","九头");
System.out.println(""+redisTemplate.opsForValue().get("key1"));
System.out.println(""+redisTemplate.opsForValue().get("key2"));
}