SpringBoot 整合redis缓存

使用synchronized+双重判断 可解决缓存击穿问题

1.导入springboot redis依赖

<!--redis依赖,当前方式像mybatis与spring整合,通过工厂,创建实例,再操作实例-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.在appliction.properties中配置redis,保证应用运行环境中已经安装了redis并设置了123456(自定义)密码

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.maxIdle=8
spring.redis.minIdle=4
spring.redis.maxTotal=8
spring.redis.maxWaitMillis=6000
spring.redis.timeout=6000
spring.redis.shutdownTimeout=100

3.使用redis

@Service
public class UserServiceImpl implements UserService{

	//在需要使用的类中注入redis依赖
	@Autowired
	private RedisTemplate redisTemplate;

	//在具体方法内获取redis缓存数据
	public User getUserById(String userid){
        //========此处可使用BloomFilter(布隆过滤器)拦截数据库中不存在的userId,防止缓存穿透============
        //从redis中获取缓存数据
		User user =(User)redisTemplate.opsForValue().get(userid);
        //synchronized+双重判断(防止缓存击穿)
        if (user == null) {  
		    synchronized (this.getClass()) {
			    user = redisTemplate.opsForValue().get(userid);
			    //关键核心再次判断
                if (user == null) {
			        //当缓存失效后让一个线程到db中获取数据并更新redis缓存
                    User user= (User)UserMapper.selectUserById(userid);
                    //key, value, ExpirationTime
			        redisTemplate.opsForValue().set(userid, user, Duration.ofDays(15));
			        return user;
			    }else {
			        return user;
			    }
		    }
		} else {
		    return user;
		}
	}
}

4.拓展

判断redis服务是否正在运行
<!--redis依赖,当然也可以通过该方式操作redis,像spring与MySQL结合,通过操作连接池,获取实例操作数据库-->
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
</dependency>
try {
	Jedis jedis = new Jedis(redisHost,redisPort);
	//查看服务是否运行,避免产生过多String对象,使用redisHost变量接收
	String ping = jedis.ping();
	boolean pong = ping.equalsIgnoreCase("PONG");
	if(pong){
		log.info("redis服务连接成功且在运行状态!");	
	}
} catch (Exception e) {
	log.error("redis服务不在运行状态!");
}
经验分享 程序员 微信小程序 职场和发展