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")//我们可以自定义一个redisTemplate来替换这个默认的!
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {
//默认的RedisTemplate 没有过多的设置,redis对象都是需要序列化的!
//两个泛型都是Object类型,Object的类型,我们使用需要强制转换<String,Object>
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean//由于String 是redis中最常用的类型,所以单独出来一个bean!
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
整合测试
1、导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置连接
# 配置redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
3、测试
@SpringBootTest
class SpringbootRedisApplicationTests {
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Test
void contextLoads() {
//redisTemplate 操作不同的数据类型
//opsForValue //操作字符串 类似String
//opsForList //操作List 类似List
//opsForSet //opsForHash //opsForZSet //opsForGeo
//除了基本的操作,我们常用的方法都可以直接通过redisTemplate操作,比如事务,和基本的CRUD
redisTemplate.opsForValue().set("myKey","myValue");
System.out.println(redisTemplate.opsForValue().get("myKey"));
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: