一、添加maven依赖
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.8.5</version>
</dependency>
二、代码方式配置Bean
package com.sf.gis.boot.rcboot.config;
import cn.hutool.core.util.StrUtil;
import com.github.benmanes.caffeine.cache.*;
import com.sf.gis.boot.rcboot.entity.CommunityStatist;
import com.sf.gis.boot.rcboot.service.ICommunityStatistService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
/**
* @author 80004819
* @ClassName:
* @Description:
* @date 2020年09月21日 15:50:52
*/
@Configuration
@Slf4j
public class CaffeineConfig {
@Autowired
private ICommunityStatistService iCommunityStatistService;
/**
* 手动加载缓存
* @return
*/
@Bean("cache")
public Cache<String, Object> cache() {
Cache<String, Object> cache = Caffeine.newBuilder().initialCapacity(500)
.maximumSize(100000)
// .weakKeys()
// .weakValues()
.softValues()
.expireAfterWrite(20, TimeUnit.SECONDS)
.expireAfterAccess(20, TimeUnit.SECONDS)
//手动加载cache不支持写入后自动刷新
// .refreshAfterWrite(30, TimeUnit.SECONDS)
.removalListener((key, value, cause) -> log.info("移除的key:{},移除的value:{},移除原因:{}", key, value, cause))
.recordStats()
.build();
return cache;
}
/**
* 自动加载缓存
* @return
*/
@Bean("loadingCache")
public LoadingCache<String, Object> loadingCache() {
LoadingCache<String, Object> cache = Caffeine.newBuilder().initialCapacity(500)
.maximumSize(100000)
// .weakKeys()
// .weakValues()
.softValues()
.expireAfterWrite(500, TimeUnit.SECONDS)
.expireAfterAccess(500, TimeUnit.SECONDS)
.refreshAfterWrite(300, TimeUnit.SECONDS)
.removalListener(
(key, value, cause) ->
log.info("移除咯key:{},移除的value:{},移除原因:{}", key, value, cause)
)
.recordStats()
.build(key -> createValue(key));
return cache;
}
private Object createValue(String key) {
return null;
}
/**
* 异步加载缓存
* @return
*/
@Bean("asyncLoadingCache")
public AsyncLoadingCache<String, Object> asyncLoadingCache() {
AsyncLoadingCache<String, Object> AsyncLoadingCache = Caffeine.newBuilder().initialCapacity(500)
.maximumSize(100000)
//异步加载cache不支持弱引用和软引用
//.weakKeys()
//.weakValues()
.expireAfterWrite(20, TimeUnit.SECONDS)
.expireAfterAccess(20, TimeUnit.SECONDS)
.refreshAfterWrite(10, TimeUnit.SECONDS)
.removalListener((key, value, cause) -> log.info("移除的key:{},移除的value:{},移除原因:{}", key, value, cause))
.recordStats()
.buildAsync(key -> createValue(key));
return AsyncLoadingCache;
}
}
三、业务代码中使用缓存机制
package com.sf.gis.boot.rcboot.controller;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.sf.gis.boot.rcboot.entity.CommunityStatist;
import com.sf.gis.boot.rcboot.service.ICommunityStatistService;
import com.sf.gis.boot.rcboot.util.JsonResponse;
import com.sf.gis.boot.rcboot.vo.CommunityStatistVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.Optional;
import static com.sf.gis.boot.rcboot.util.JsonResponse.STATUS_FAILED;
import static com.sf.gis.boot.rcboot.util.JsonResponse.STATUS_SUCCESS;
/**
* <p>
* 社区管理表 前端控制器
* </p>
*
* @author 段朝旭
* @since 2020-09-11
*/
@RestController
@RequestMapping("/community-statist")
@Api(tags = "社区管理")
@Slf4j
public class CommunityStatistController {
@Autowired
private ICommunityStatistService iCommunityStatistService;
@Autowired
private Cache<String, Object> cache;
@ApiOperation("根据aoi_id查询社区管理数据")
@GetMapping("/getCommunityByAoiId")
public JsonResponse getCommunityByAoiId(@RequestParam("aoi_id") String aoi_id) {
try {
CommunityStatist aoiStatist = iCommunityStatistService.getByAoiId(aoi_id);
//查询人口统计总数,法人总数,房屋总数,房屋使用情况总数
LinkedHashMap<String, Object> resultMap = Optional.ofNullable(iCommunityStatistService.staticCommunity(aoi_id)).orElse(new LinkedHashMap<>());
resultMap.put("aoiStatist", aoiStatist);
return JsonResponse.ok(STATUS_SUCCESS, resultMap);
} catch (Exception e) {
log.error("error", e);
return JsonResponse.error("error");
}
}
/**
* 获取设备树形结构数据
*
* @return
*/
@GetMapping("/getCommunityTreeByAoiId")
@ApiOperation("根据aoiId获取社区管理树形结构")
public JsonResponse getCommunityTreeByAoiId(@RequestParam("aoi_id") String aoi_id) {
JsonResponse result = new JsonResponse();
try {
if (StrUtil.isBlank(aoi_id)) {
result.setData(STATUS_FAILED, "aoi_id不能为空");
return result;
}
CommunityStatistVo resultTree = iCommunityStatistService.getCommunityTreeByAoiId(aoi_id);
result.setData(STATUS_SUCCESS, resultTree);
return result;
} catch (Exception e) {
log.error("error", e);
result.setData(STATUS_FAILED, null);
return result;
}
}
@GetMapping("/getCommunityByAoiIdWithCache")
@ApiOperation("根据aoi_id查询社区管理数据(带有缓存~~过期时间20s)")
public JsonResponse getCommunityByAoiIdCache(@RequestParam("aoi_id") String aoi_id) {
try {
//从缓存中获取社区数据
Object communityObj = cache.get("community-" + aoi_id, s -> iCommunityStatistService.getByAoiId(aoi_id));
CommunityStatist aoiStatist = ObjectUtil.isNotEmpty(communityObj) ? (CommunityStatist) communityObj : null;
//从缓存中获取查询人口统计总数,法人总数,房屋总数,房屋使用情况总数
Object linkedHashMapObj = cache.get("communityStatist-" + aoi_id, s -> Optional.ofNullable(iCommunityStatistService.staticCommunity(aoi_id)).orElse(new LinkedHashMap<>()));
LinkedHashMap<String, Object> resultMap = (LinkedHashMap<String, Object>) linkedHashMapObj;
resultMap.put("aoiStatist", aoiStatist);
return JsonResponse.ok(STATUS_SUCCESS, resultMap);
} catch (Exception e) {
log.error("error", e);
return JsonResponse.error("error");
}
}
/**
* 获取设备树形结构数据
*
* @return
*/
@GetMapping("/getCommunityTreeByAoiIdWithCache")
@ApiOperation("根据aoiId获取社区管理树形结构(带有缓存~~过期时间20s)")
public JsonResponse getCommunityTreeByAoiIdWithCache(@RequestParam("aoi_id") String aoi_id) {
JsonResponse result = new JsonResponse();
try {
if (StrUtil.isBlank(aoi_id)) {
result.setData(STATUS_FAILED, "aoi_id不能为空");
return result;
}
//从缓存中获取社区管理树形结构数据
Object o = cache.get("communityTree-" + aoi_id, s -> iCommunityStatistService.getCommunityTreeByAoiId(aoi_id));
CommunityStatistVo resultTree = ObjectUtil.isNotEmpty(o)? (CommunityStatistVo)o:null;
result.setData(STATUS_SUCCESS, resultTree);
return result;
} catch (Exception e) {
log.error("error", e);
result.setData(STATUS_FAILED, null);
return result;
}
}
}