说起缓冲,首先想到的肯定是redis,所以,我们在用redis的一些工具类的时候,一般的思路都是这样的:
- 先查询缓冲是否存在
- 缓冲存在,则直接从缓冲中查询出来,返回给前端
- 缓冲不存在,然后再数据库中查询,然后放在缓冲中,返回给前端。
根据上面的逻辑,我们有了下面的这段代码:
@Autowired
private UserMapper userMapper;
@Autowired
private RedisTemplate redisTemplate;
public int getUserByTotal() {
//字符串的序列化器
RedisSerializer redisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(redisSerializer);
//查询缓存
Integer userByTotal = (Integer) redisTemplate.opsForValue().get("total");
//双重检测锁
if (null == userByTotal) {
synchronized (this) {
//从redis获取一下
userByTotal = (Integer) redisTemplate.opsForValue().get("total");
if (null == userByTotal) {
//缓存为空,查询一遍数据库
userByTotal = userMapper.selectUserByTotal();
//把数据库查询出来的数据,放入redis中
redisTemplate.opsForValue().set("userByTotal", userByTotal);
}
}
}
return userByTotal;
}
假如很多代码都需要放在redis中,那么 我们存在大量重复的逻辑,那就是判断缓冲中是否为空,不为空查库,查库之后的数据放在缓冲中。能不能将这段逻辑独立出来呢?
当然可以,我们的事务不就是独立出来了吗?仅仅一个注解。spring的注解@Cacheable和事务注解的原理类似,也是根据AOP的原理做一个切面。具体关于Cacheable的理论性知识我们下一篇博客讲解,现在我们主要是实践如何集成。
搭建好springboot框架之后,我们首先需要添加redis的jar包。
<!-- 加载spring boot redis包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
然后需要在springboot的Aplication中添加@EnableCaching注解
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@EnableCaching
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println("启动成功------------------------");
}
}
接下来,我们直接在类或者是方法上面添加开启缓冲的注解,开启之后,方法的返回值将直接存放到了缓冲中。
@Service
public class DemoServiceImpl implements DemoService {
@Override
@Cacheable(value = "userCache",key = "#root.methodName")
//value标示缓冲的命名空间,key表示该缓冲的key值,
// #root.methodName表示以方法名称作为key值,方法的返回值表示缓冲的value值
public UserDto getUser(){
System.out.println("查后台数据");
UserDto dto=new UserDto();
dto.setName("cache");
dto.setSex("woman");
return dto;
}
}
这样,我们只需要在配置文件中加入redis的链接地址,启动工程,我们就可以看到redis中已经存在该key值了。再次访问,则直接走的是缓冲。
demo已上传git,地址为: https://github.com/feizai1010/springboot_cache.git