Spring内置缓存cache
cache介绍
- cache缓存是spring自带的内置缓存,可以减少系统开销,提高系统效率。
- cache内置缓存无需网络,数据存放在java内存里。一般做为二级缓存用,缓存地区、热点等数据,数据不会经常修改。如需缓存大量数据,可用Redis缓存
使用cache缓存 提供案例
- 引入相关依赖
org.springframework.boot
spring-boot-starter-cache
com.github.ben-manes.caffeine
caffeine
2.7.0
- 创建本地caffeine缓存配置CaffeineConfig工具类
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.Duration;
import java.util.ArrayList;
/**
* 本地caffeine缓存配置
* @author LiZan
* @version 1.0
* @date 2023/2/10 9:54
*/
@Configuration
public class CaffeineConfig {
public enum CacheEnum {
/**
* @date 16:34 2020/10/27
* 第一个cache
**/
FIRST_CACHE(300, 20000, 300),
/**
* @date 16:35 2020/10/27
* 第二个cache
**/
SECOND_CACHE(60, 10000, 200);
private int second;
private long maxSize;
private int initSize;
CacheEnum(int second, long maxSize, int initSize) {
this.second = second;
this.maxSize = maxSize;
this.initSize = initSize;
}
}
@Bean("caffeineCacheManager")
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
ArrayList caffeineCaches = new ArrayList<>();
for (CacheEnum cacheEnum : CacheEnum.values()) {
caffeineCaches.add(new CaffeineCache(cacheEnum.name(),
Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(cacheEnum.second))
.initialCapacity(cacheEnum.initSize)
.maximumSize(cacheEnum.maxSize).build()));
}
cacheManager.setCaches(caffeineCaches);
return cacheManager;
}
}
- 创建CaffeineUtils工具类,用于增删改查
import org.springframework.boot.CommandLineRunner;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* Caffeine缓存工具类
* @author LiZan
* @version 1.0
* @date 2023/2/10 10:41
*/
@Component
public class CaffeineUtils implements CommandLineRunner {
@Resource(name = "caffeineCacheManager")
CacheManager cacheManager;
Cache cache1;
Cache cache2;
@Override
public void run(String... args) throws Exception {
cache1 = cacheManager.getCache("FIRST_CACHE");
cache2 = cacheManager.getCache("SECOND_CACHE");
}
/**
* 添加或更新缓存
*
* @param key
* @param value
*/
public void putAndUpdateCache(String key, Object value) {
cache1.put(key, value);
}
/**
* 获取对象缓存
*
* @param key
* @return
*/
public T getObjCacheByKey(String key, Class t) {
return cache1.get(key,t);
}
/**
* 根据key删除缓存
*
* @param key
*/
public void removeCacheByKey(String key) {
// 从缓存中删除
cache1.evict(key);
}
}
- 测试cache缓存,内有redis缓存,如果不用可删除redis相关代码
import com.alibaba.fastjson.JSONObject;
import com.zhengqing.demo.modules.system.entity.User;
import com.zhengqing.demo.utils.CaffeineUtils;
import com.zhengqing.demo.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author LiZan
* @version 1.0
* @date 2023/1/4 17:12
*/
@Component
public class UserService {
@Autowired
private RedisUtil redisUtil;
@Resource
private CaffeineUtils caffeineUtils;
public void setUser(User user) {
System.out.println("缓存信息"+user.toString());
caffeineUtils.putAndUpdateCache("123",user);
String s = JSONObject.toJSONString(user);
System.out.println(s);
redisUtil.set("123",s);
}
public User getUser(String id) {
// 一级缓存从redis拿数据
if(redisUtil.hasKey(id)){
System.out.println("进去redis缓存");
String s = redisUtil.get(id);
User user = JSONObject.parseObject(s,User.class);
user.setIntro("123123");
return user;
}
// 从cache 拿user缓存
User user = caffeineUtils.getObjCacheByKey(id, User.class);
// cache缓存没有,从数据库查
if(null == user){
System.out.println("双重缓存失效,进入数据库查询");
User user1 = createUser();
//保存cache缓存里
setUser(user1);
return user1;
}
return user;
}
private User createUser(){
User zhangsan = User.builder().id(123L).name("ZHANGSAN").age(123).build();
return zhangsan;
}
/**
* 使用@CachePut注解的方法,一定要有返回值,该注解声明的方法缓存的是方法的返回结果。
* it always causes the
* method to be invoked and its result to be stored in the associated cache
**/
//@CachePut(key = "#user.getId()", value = "SECOND_CACHE", cacheManager = "caffeineCacheManager")
//public User setUser(User user) {
// System.out.println("已经存储进缓存了");
// return user;
//}
public void deleteUser(String id) {
System.out.println("缓存删除了");
redisUtil.delete(id);
caffeineUtils.removeCacheByKey(id);
}
//@Cacheable(key = "#id", value = "SECOND_CACHE", cacheManager = "caffeineCacheManager")
//public User getUser(Integer id) {
// System.out.println("从数据库取值");
// //模拟数据库中的数据
// return null;
//}
import com.zhengqing.demo.lizan.service.UserService;
import com.zhengqing.demo.modules.common.dto.output.ApiResult;
import com.zhengqing.demo.modules.system.entity.User;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author LiZan
* @version 1.0
* @date 2023/2/10 10:51
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping(value = "/getUser", produces = "application/json;charset=utf-8")
@ApiOperation(value = "获取用户对象", httpMethod = "GET", response = ApiResult.class)
public ApiResult getUser() {
return ApiResult.ok(userService.getUser("123"));
}
@GetMapping(value = "/setUser", produces = "application/json;charset=utf-8")
@ApiOperation(value = "缓存User数据", httpMethod = "GET", response = ApiResult.class)
public ApiResult setUser() {
userService.setUser(User.builder().id(123L).name("ZHANGSAN").age(123).build());
return ApiResult.ok();
}
@GetMapping(value = "/delUser", produces = "application/json;charset=utf-8")
@ApiOperation(value = "删除缓存", httpMethod = "GET", response = ApiResult.class)
public ApiResult deleteUser() {
userService.deleteUser("123");
return ApiResult.ok();
}
}
- 执行IP:端口/setUser,getUser,delUser测试结果如下
