记录自己第一次写的缓存
程序员文章站
2022-03-04 16:16:03
...
这是我第一次接触到缓存这一个功能,不是写在redis上,而是在内存上,利用list集合。在这次代码的编写中让我对list集合更加的熟悉。以此记录我的成长。
代码
@Repository(value = "orderTypeDetailDao")
public class OrderTypeDetailDao extends CommonDao<OrderTypeDetail> {
//版本号
public static Integer version = -1;
public static volatile long t = 0;
public static final String OrderTypeDetail_KEY = "version:orderTypeDetailKey";
private static List<OrderType> orderTypeList = new ArrayList<>();
public static OrderType[] getOrderTypeDetail(){
//先调用下方的刷新方法,如果集合不为空就清空
refreshOrderTypeDetail();
if (orderTypeList.size() == 0) {
//加锁
synchronized (orderTypeList) {
if (orderTypeList.size() == 0) {
OrderTypeDetail orderTypeDetail = new OrderTypeDetail();
//设置查询的name属性
orderTypeDetail.setName("base.system.orderType");
try{
//查询
orderTypeDetail.load();
//判断是否查询到
if(orderTypeDetail.getIsLoad()){
//获取值
String value = orderTypeDetail.getValue();
//拆分字符串
String[] split = value.split(",");
//新建集合存下方遍历到的
List<OrderType> orderTypeListTmp = new ArrayList<>();
//遍历
for(int i=0;i<split.length;i++){
String s = split[i];
try {
OrderType orderType = OrderType.valueOfTypeCode(s);
//添加到集合中
orderTypeListTmp.add(orderType);
} catch (Exception e) {
continue;
}
}
//将集合付给缓存集合
orderTypeList = orderTypeListTmp;
}
else{
//获取所有的枚举
orderTypeList = Arrays.asList(OrderType.values());
}
}
catch (Exception ex){
//获取所有的枚举
orderTypeList = Arrays.asList(OrderType.values());
}
}
}
}
OrderType[] ret = new OrderType[orderTypeList.size()];
return orderTypeList.toArray(ret);
}
private static void refreshOrderTypeDetail(){
long time=System.currentTimeMillis();
if(time>t){
Integer ver = JedisClientPool.getInstance().getInt(OrderTypeDetail_KEY);
if (ver != null && ver > version) {
orderTypeList.clear();
version = ver;
}
t=time+10000;
}
}
public static void refresh(){
if(!JedisClientPool.getInstance().exists(OrderTypeDetail_KEY)){
JedisClientPool.getInstance().set(OrderTypeDetail_KEY, "0");
}else{
JedisClientPool.getInstance().incr(OrderTypeDetail_KEY);
}
}
@Override
public String getTableName() {
return "base_sys_order_type";
}
@Override
public void insertOrUpdate(OrderTypeDetail obj){
ThreadContext threadContext = ThreadContext.getThreadContext();
threadContext.startTransaction();
try {
super.insertOrUpdate(obj);;
threadContext.commit();
} catch (Exception e) {
threadContext.rollback();
e.printStackTrace();
}
}}
上一篇: 课时108.外边距属性(掌握)
下一篇: Linux操作系统问题