Redis
1,导入依赖:
< dependency>
< groupId>org.springframework.boot</ groupId>
< artifactId>spring-boot-starter-data-redis</ artifactId>
< dependency>
底层: lettuce连接池
在springboot2.x之后,原来的jedis被替换为了lettuce
jedis:采用的直连,多个线程操作的话,是不安全的,如果想避免不安全,就要用jedis pool连接池! BIO
lettuce:采用netty,实例可以在多个线程中共享,不存在线程不安全的情况!可以减少线程数量了,更像NIO模式。
源码分析
public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = “redisTemplate”)//我们可以自己定义一个,来替换
@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;
}
@Bean
@ConditionalOnMissingBean//由于String是最常用类型,所以单独提出来了一个bean
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
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,配置连接
#springboot所有的配置类,都有一个自动配置类 RedisAutoConfiguration
#自动配置类 都会绑定一个properties, RedisProperties 这个文件绑定application.yaml
spring:
redis:
host: 127.0.0.1
port: 6379
3,测试
@SpringBootTest
class RredisApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
在企业开发中,我们一般不会使用下面原生的方式,一般自己写RedisUtil,里面封装下面原生的方法。可以去网上找
//RedisTemplate 操作不同的数据类型,api和我们的指令是一样的
//opsForValue 操作字符串,类似String
//opsForList 操作list,类似Slist
//opsForSet
//opsForHash
//opsForGeo
//opsForZSet
//除了基本的操作,常用的方法都可以直接通过RedisTemplate操作,比如 事务,和基本的CRUD
//获取redis连接对象
// RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
// connection.flushDb();
// connection.flushAll();
redisTemplate.opsForValue().set(“mykey”,“kuangshen”);
System.out.println(redisTemplate.opsForValue().get(“mykey”));
}
}
实际开发中,需要存放中文等,使用默认的Template太low了,(默认的序列化使用JDK的序列化,会存在转义等问题)我们需要自己写一个配置类
@Configuration
public class RedisConfig {
//编写自己的redisTemplate
@Bean
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
//这里可以配置具体的序列化方式
网上有标准的
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
Test里面测试
@Test
void test(){
//真实开发使用JSON传递对象
User user = new User(“狂神”,3);
String jsonUser = JSON.toJSONString(user);
redisTemplate.opsForValue().set(“user”,jsonUser);
System.out.println(redisTemplate.opsForValue().get(“user”));
}