springboot 整合 redis
导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
自动配置
- RedisAutoConfiguration 自动配置类。RedisProperties属性类 -> spring.redis.xxxx 是对 redis的配置
- 连接工厂是准备好的,LettuceConnectionConfiguration、JedisConnectionConfiguration
- 自动注入了 RedisTemplate<Object,Object>
- 自动注入了 StringRedisTemplate: k-v 都是String
- key:value
- 底层只要我们使用StringRedisTemplate、RedisTemplate 就可以操作 redis
redis配置
spring:
redis:
url: redis://user:password@example.com:6379
# redis://用户名:密码@地址:端口号
host: 主机地址
port: 端口号
password: 用户名:密码
使用
redisTemplate 与 Lettuce
@Autowired
StringRedisTemplate redisTemplate;
@Test
void testRedis(){
ValueOperations<String,String> operations=redisTemplate.opsForValue();
operations.set("hello","world");
String hello = operations.get("hello");
System.out.println(hello);
}
切换为 Jedis
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
spring:
redis:
client-type: jedis
补充
redisTemplate.opsForValue().increment(uri);
// 计数加一
关于 Filter、Interceptor
他们几乎拥有相同的功能
区别是:
- Filter 是 servlet 定义的额原生组件。好处是脱离Spring应用也能使用
- Interceptor是spring定义的接口,可以使用spring的自动装配等功能