spring boot cache 整合 redis

30 篇文章 3 订阅
8 篇文章 0 订阅

 关于 Spring Cache 注解请查看Spring Cache 注解详解

 Redis的安装教程:https://blog.csdn.net/LDY1016/article/details/76083162

下面进入正题。。。

1、在pom.xml中添加redis的依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-pool2</artifactId>
</dependency>

2、在application.properties文件中配置redis缓存

#redis
spring.redis.host=127.0.0.1
spring.redis.port = 6379
#spring.redis.password=
# 连接超时时间(毫秒)
spring.redis.timeout=10000
# Redis默认情况下有16个分片,这里配置具体使用的分片
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0


#cache
# 一般来说是不用配置的,Spring Cache 会根据依赖的包自行装配
spring.cache.type=redis

3、配置RedisConfig

package com.ldy.bootv2.demo;

import java.time.Duration;

import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

		redisTemplate.setConnectionFactory(redisConnectionFactory);
		redisTemplate.setKeySerializer(keySerializer());
		redisTemplate.setHashKeySerializer(keySerializer());
		redisTemplate.setValueSerializer(valueSerializer());
		redisTemplate.setHashValueSerializer(valueSerializer());
		return redisTemplate;
	}

	@Primary
	@Bean
	public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
		// 缓存配置对象
		RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();

		redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L)) // 设置缓存的默认超时时间:30分钟
				.disableCachingNullValues() // 如果是空值,不缓存
				.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer())) // 设置key序列化器
				.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer()))); // 设置value序列化器

		return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
				.cacheDefaults(redisCacheConfiguration).build();
	}

	private RedisSerializer<String> keySerializer() {
		return new StringRedisSerializer();
	}

	private RedisSerializer<Object> valueSerializer() {
		return new GenericJackson2JsonRedisSerializer();
	}
}

4、在启动类上加上@EnableCaching注解开启缓存

package com.ldy.bootv2.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@EnableCaching
@SpringBootApplication
public class BootV2App {

	public static void main(String[] args) {
		SpringApplication.run(BootV2App.class, args);
	}
}

5、在service层加入缓存

package com.ldy.bootv2.demo.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import com.ldy.bootv2.demo.entity.UserEntity;
import com.ldy.bootv2.demo.mapper.UserMapper;

@Service
public class UserService {

	@Autowired
	UserMapper userMapper;

	@Cacheable(value = "user", key = "'list'", unless = "#result == null") // unless="#result == null"表示返回结果为空时不缓存
	public List<UserEntity> getAll() {
		return userMapper.getAll();
	}

	@Cacheable(value = "user", key = "#id", unless = "#result == null") // unless="#result == null"表示返回结果为空时不缓存
	public UserEntity getOne(Integer id) {
		return userMapper.getOne(id);
	}

	@CachePut(value = "user", key = "#entity.id") // 将返回结果更新到缓存中
	@CacheEvict(value = "user", key = "'list'") // list数据有变更,清空list缓存
	public UserEntity insert(UserEntity entity) {
		userMapper.insert(entity);
		return entity;
	}

	@CachePut(value = "user", key = "#entity.id") // 将返回结果更新到缓存中
	@CacheEvict(value = "user", key = "'list'") // list数据有变更,清空list缓存
	public UserEntity update(UserEntity entity) {
		userMapper.update(entity);
		return entity;
	}

	@Caching(evict = { @CacheEvict(value = "user", key = "#id"), @CacheEvict(value = "user", key = "'list'") })
	// @CacheEvict(value = "user", key = "#id")//清除指定id的缓存
	// @CacheEvict(value="user", allEntries=true)//allEntries为true时,将忽略指定的key,清除全部user缓存
	public void delete(Integer id) {
		userMapper.delete(id);
	}

}

上述代码亲测有效,有问题欢迎留言!!!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值