基本使用
首先添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
默认会连接到localhost:6379 所以项目中不需要进行任何的配置就可以使用自动配置已经配置好的 3个类型 RedisConnectionFactory, StringRedisTemplate, RedisTemplate
配置:
@Bean
public RedisTemplate redisTemplate2(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
//这里配置一个序列化器
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
template.setValueSerializer(genericJackson2JsonRedisSerializer);
template.setHashValueSerializer(genericJackson2JsonRedisSerializer);
return template;
}
server类:
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void doSth(){
redisTemplate.opsForValue().set("boot","test");
stringRedisTemplate.opsForValue().set("bootStr","test2");
}
启动类:
@SpringBootApplication
public class Ch08Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Ch08Application.class, args);
}
@Autowired
private RedisDemo redisDemo;
@Override
public void run(String... args) throws Exception {
redisDemo.doSth();
}
}