package com.jt.provider.controller;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
@Slf4j
@RefreshScope
@RestController
public class ProviderCacheController {
/*
*为了防止每次写 添加注解@Slf4j 该注解来自lombok 因为父工程添加了该依赖此处无语再引入
*
*private static Logger log =
* LoggerFactory.getLogger(ProviderCacheController.class);
*/
/**
* 从配置文件读取值给属性
* 依赖注入
* 默认是false
*/
@Value("${useLocalCache:false}")
private boolean useLocalCache;
@GetMapping("/provider/cache01")
public String doUserLocalCache01(){
return String.format("userLocalCache's value is %s", useLocalCache);
}
private CopyOnWriteArrayList<String> cache = new CopyOnWriteArrayList<>();
@GetMapping("/provider/cache02")
public List<String> doUserLocalCache02(){
//1.不开启本地缓存
if(!useLocalCache){
//如果是true 即useLocalCache是false
log.info("select ");
// return "select";
return Arrays.asList("a","b","c");
}
/**开启了本地缓存
* 2.读取数据库存放到cache
*/
if(cache.isEmpty()){
//this是当前类
synchronized (this){
if(cache.isEmpty()){
//模拟从数据库中获取数据 数据是数组的形式
List<String> data = Arrays.asList("a","b","c");
cache.addAll(data);
}
}
}
//开启本地缓存 并且缓存不为空
return cache;
//return String.format("userLocalCache's value is %s", useLocalCache);
}
}
多线程锁读取本地cache案例
最新推荐文章于 2024-03-24 21:42:51 发布