SpringBoot 使用Redis
pom.xml导入Redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在配置文件中配置基本信息
spring:
redis:
host: 192.168.169.133
port: 6379 #开启允许远程连接 允许Redis远程连接:注释掉 redis.conf 文件中的 bind 127.0.0.1
password: 123456
database: 0
jedis:
pool:
max-active: 8 # 最大连接数
max-wait: 1ms # 最大阻塞时间 设为-1表示无限制。
max-idle: 4 #接池的最大数据库连接数。设为0表示无限制。
min-idle: 0
在项目中引入配置类,设置序列化器(非必须步骤,只是为了便于在reids工具中查看)。
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object,Object> redisTemplate=new RedisTemplate<>();
// 默认的序列化器: new JdkSerializationRedisSerializer()
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}
使用自动注入 RedisTemplate 对象,使用 RedisTemplate 对象操作Reids
Redis简单示例:缓存String类型的数据
@Autowired
private RedisTemplate redisTemplate;
@GetMapping
public String getInfo(){
//Redis简单示例:缓存String类型的数据
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set(key,value);
valueOperations.set(key,value,time);
valueOperations.set(key,value,TimeUnit);
//获取String类型的缓存数据
valueOperations.get(key)
//删除Redis中指定的key,通用操作直接使用redisTemplate操作即可,
redisTemplate.delete(key)
}
缓存其他类型的数据,使用 RedisTemplate 创建指定的对象即可。
//缓存Hash类型的数据
redisTemplate.opsForHash();
//新增hashMap值
redisTemplate.opsForHash().put(key, hashKey, value)
//以map集合的形式添加键值对
public void hPutAll(String key, Map<String, String> maps) {
redisTemplate.opsForHash().putAll(key, maps);
}
//删除一个或者多个hash表字段
public Long hashDelete(String key, Object... fields) {
return redisTemplate.opsForHash().delete(key, fields);
}
... ...
//缓存List集合类型的数据
redisTemplate.opsForList();
//通过索引获取列表中的元素
redisTemplate.opsForList().index(key, index);
//获取列表指定范围内的元素(start开始位置, 0是开始位置,end 结束位置, -1返回所有)
redisTemplate.opsForList().range(key, start, end);
//存储在list的头部,即添加一个就把它放在最前面的索引处
redisTemplate.opsForList().leftPush(key, value);
//把多个值存入List中(value可以是多个值,也可以是一个Collection<V> value)
redisTemplate.opsForList().leftPushAll(key, value);
... ...
//Set类型
//添加元素
redisTemplate.opsForSet().add(key, values);
//移除元素(单个值、多个值)
redisTemplate.opsForSet().remove(key, values);
//删除并且返回一个随机的元素
redisTemplate.opsForSet().pop(key);
//获取集合的大小
redisTemplate.opsForSet().size(key);
//判断集合是否包含value
redisTemplate.opsForSet().isMember(key, value);
//获取两个集合的交集(key对应的无序集合与otherKey对应的无序集合求交集)
redisTemplate.opsForSet().intersect(key, otherKey);
... ...
//zSet类型
//ZSetOperations提供了一系列方法对有序集合进行操作添加元素(有序集合是按照元素的score值由小到大进行排列)
redisTemplate.opsForZSet().add(key, value, score);
//删除对应的value,value可以为多个值
redisTemplate.opsForZSet().remove(key, values);
//增加元素的score值,并返回增加后的值
redisTemplate.opsForZSet().incrementScore(key, value, delta);
//返回元素在集合的排名,有序集合是按照元素的score值由小到大排列
redisTemplate.opsForZSet().rank(key, value);
//返回元素在集合的排名,按元素的score值由大到小排列
redisTemplate.opsForZSet().reverseRank(key, value);
//获取集合中给定区间的元素(start 开始位置,end 结束位置, -1查询所有)
redisTemplate.opsForZSet().reverseRangeWithScores(key, start,end);
... ...
Spring Boot中使用Spring Cache
Spring Cache是一个框架,实现了基于注解的缓存功能。只需要增加一个注释,就可以实现缓存功能。
Spring Cache提供了一层抽象,底层可以切换不同的Cache实现。具体就是通过CacheManager接口来统一不同的缓存技术。
CacheManager是Spring提供的各种缓存技术的抽象接口。
针对不同的缓存技术,需要实现不同的CacheManager
在Spring Boot项目中,使用缓存技术只需要在项目中导入相关缓存技术的的依赖包,并在启动类上使用 @EnableCaching 开启缓存功能即可。
修改配置文件,增加cache,指定Redis作为缓存产品
spring:
cache:
redis:
time-to-live: 180000 #设置缓存过期时间
redis:
database: 0
host: 127.0.0.1
jedis:
pool:
max-idle: 8
max-wait: 1ms
max-active: 8
min-idle: 0
Spring cache常用注解说明:
注释 | 说明 |
---|---|
@EnableCaching | 开启缓存注释功能 |
@Cacheable | 在方法执行前spring先查看缓存中是否有数据,如果有,直接返回缓存数据;没有,调用方法并将方法返回值放到缓存中 |
@CachePut | 将方法的返回值放到缓存中 |
@CacheEvict | 将一条或多条数据从缓存中删除 |
@Caching | 有时候我们可能组合多个Cache注解使用;比如用户新增成功后,我们要添加id–>user;username—>user;email—>user的缓存;此时就需要@Caching组合多个注解标签了。 |
SpringCache整合redis
添加依赖项,启动类添加@EnableCaching
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
@EnableCaching
@SpringBootApplication
public class RedisCacheApplication {
public static void main(String[] args) {
SpringApplication.run(RedisCacheApplication.class,args);
}
}
配置yml文件,上边有提到
创建Redis的配置类
需要被缓存类实现Serializable接口。
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// 创建一个JSON格式序列化对象,对缓存数据的key和value进行转换
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
// 解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
return template;
}
这个就是一个简单的RedisTemplate,只是配置了键值对的序列化方式而已,
你其实也可以这样做:都是配置一下redisTemplate
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory){
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(RedisSerializer.string());
redisTemplate.setValueSerializer(RedisSerializer.json());
return redisTemplate;
}
在方法上面使用缓存
这里代表的是:
根据Id查询品牌数据,然后开启缓存;
缓存的名称的头部是brands开头,例如:brands:xx:xx
缓存的key使用传入进来的id进行设置;
开启条件缓存,只有id是2的倍数,redis才进行缓存
@Cacheable(value = "brands",key = "#id",condition = "#id%2==0")
public Brand getById(Integer id) {
Brand brand = brandMapper.selectById(id);
return brand;
}
自定义缓存管理器
除了上面的这种简单做法,我们还可以自己添加一些缓存规则,这就需要用到缓存管理器了。
@Bean("cacheManager")
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory){
//通过下面的instanceConfig()方法获得一个RedisCacheConfiguration;
RedisCacheConfiguration configuration = instanceConfig();
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(configuration)//设置默认参数
.transactionAware()//事务感知
.build();
}
private RedisCacheConfiguration instanceConfig(){
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(60L))//设置过期时间为60秒
.disableCachingNullValues();//不缓存空对象
}
然后有了缓存管理器之后,你也就可以在代码中运用他了,通过给@EnableCache的manager属性添加值就行了
@Override
@Cacheable(value = "brands",key = "#id",condition = "#id%2==0",cacheManager = "cacheManager")
public Brand getById(Integer id) {
Brand brand = brandMapper.selectById(id);
return brand;
}
hingNullValues();//不缓存空对象
}
然后有了缓存管理器之后,你也就可以在代码中运用他了,通过给@EnableCache的manager属性添加值就行了
```java
@Override
@Cacheable(value = "brands",key = "#id",condition = "#id%2==0",cacheManager = "cacheManager")
public Brand getById(Integer id) {
Brand brand = brandMapper.selectById(id);
return brand;
}