在现系统中使用了一个字典表,更新或插入字典表需要做Redis缓存

    @Override
@Cache(name = Constants.REDIS_PREFIX_DIC, desc = "变更字典后更新")
public int editDict(DictEntity data) {
int editCnt = -1;
Date d = new Date();
Integer dictId = data.getDictId();
data.setUpdatedDate(d);
if (dictId != null && dictId > 0) {
editCnt = dictDao.updatedByPrimaryKeySelective(data);
} else {
data.setCreatedDate(d);
data.setCreatedBy(data.getUpdatedBy());
editCnt = dictDao.insertSelective(data);
dictId = data.getDictId();
} dictItemsDao.deleteByDictId(dictId); List<DictItemsEntity> list = new ArrayList<DictItemsEntity>();
for (DictItemsEntity item : data.getItemsList()) {
item.setDictId(dictId);
list.add(item);
}
dictItemsDao.insertByList(list);
return editCnt;
}

在此之上使用了一个@Catch的注解,这个注解是自己重写的,做Redis缓存的更新操作

@Catch注解:

package com.jn.baseservice.annotation;

import com.jn.baseservice.common.RedisConstant;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Cache { /**
* 缓存名
*
* @return
*/
String name(); /**
* 更新范围
*
* @return
*/
String range() default RedisConstant.RANGE_WHOLE; /**
* 描述
*
* @return
*/
String desc() default "";
}

其中以下两个注解可以去:https://www.cnblogs.com/peida/archive/2013/04/24/3036689.html 中查看

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})

之后使用一个切面,用于监听Redis更改缓存的操作:

package com.jn.ssr.superrescue.config;

import com.jn.baseservice.annotation.Cache;
import com.jn.baseservice.common.RedisConstant;
import com.jn.ssr.superrescue.cache.CacheFactory;
import com.jn.ssr.superrescue.cache.DictCache;
import com.jn.ssr.superrescue.tools.SpringConfigTool; import lombok.extern.log4j.Log4j2; import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch; @Aspect
@Component
@Log4j2
/**
* 用于监听更改缓存的操作
*/
public class CacheAspect {
//切面范围:com.hhh.test.super下的service.impl 下所有的public开头的方法
@Pointcut("execution(public * com.hhh.test.super.*.*.service.impl..*.*(..))")
public void cacheCut() {
}
//这个就是以上Redis的Catch的实现
@AfterReturning(returning = "ret", pointcut = "cacheCut()", value = "@annotation(cache)")
public void doAfterReturning(Object ret, Cache cache) throws Throwable {
log.info("欢迎更改缓存:{}", ret);
StopWatch watch = new StopWatch();
watch.start(cache.name());
CacheFactory factory = (CacheFactory) SpringConfigTool.getBean(DictCache.factoryMap.get(cache.name()));
boolean result = cache.range().equals(RedisConstant.RANGE_WHOLE) ? factory.create().wholeRefresh() : factory.create().simpleRefresh(cache.name());
watch.stop();
log.info("缓存更新结果 {} taskName:{},耗时:{}ms,描述:{}", result, watch.getLastTaskName(), watch.getLastTaskTimeMillis(), cache.desc());
}
}

调用了catchFactory:其中有一个create方法,返回一个CatcherUpdate对象:

package com.jn.ssr.superrescue.cache;

public interface CacheFactory {
CacheUpdate create();
}

CatchUpdate中提供两个方法:

package com.jn.ssr.superrescue.cache;

public interface CacheUpdate {

    /**
* vue调用组件
*/
String key = "key"; String label = "label"; String id = "id"; String parentId = "parentId"; default boolean simpleRefresh(String name) {
return true;
} boolean wholeRefresh();
}

这个类的实现类是:

package com.jn.ssr.superrescue.cache.impl;

import com.jn.baseservice.common.Constants;
import com.jn.baseservice.common.RedisConstant;
import com.jn.baseservice.entity.dict.DictEntity;
import com.jn.baseservice.entity.dict.DictItemsEntity;
import com.jn.baseservice.utils.DateUtils;
import com.jn.baseservice.utils.RedisHandle;
import com.jn.ssr.superrescue.cache.CacheUpdate;
import connector.dict.DictService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; /**
* 字典类缓存
*
*/
@Component
@Log4j2
public class DicCache implements CacheUpdate { @Autowired
private RedisHandle redisHandle; @Autowired
private DictService dictService; @Override
public boolean simpleRefresh(String dicCode) {
boolean result = true;
try {
DictEntity search = new DictEntity();
search.setDictCode(dicCode);
commonAdd(search);
} catch (Exception e) {
result = false;
log.error("字典部分更新失败:", e);
}
return result;
} @Override
public boolean wholeRefresh() {
boolean result = true;
try {
commonAdd(new DictEntity());
} catch (Exception e) {
result = false;
log.error("字典全量更新失败:", e);
}
return result;
} /**
* 抽离公共部分
*
* @param search
*/
private void commonAdd(DictEntity search) {
search = new DictEntity();//需要全量更新 到REDIS_PREFIX_WEB_DIC
log.info("添加基础数据字典");
long start = System.currentTimeMillis();
List<DictEntity> list = dictService.findBatchItems(search);
Map<String, List<Map<String, String>>> dictMaps = new ConcurrentHashMap<>();
for (DictEntity tmp : list) {
String code = tmp.getDictCode();
if (tmp.getCompanyId() != null && tmp.getCompanyId() > 0) {
code += "_" + tmp.getCompanyId();
}
List<Map<String, String>> dictItems = new ArrayList<Map<String, String>>();
List<DictItemsEntity> itemsList = tmp.getItemsList();
Map<String, String> itemsMap = new LinkedHashMap<String, String>();
for (DictItemsEntity item : itemsList) {
Map<String, String> webMap = new LinkedHashMap<String, String>();
webMap.put("key", item.getDictKey());
webMap.put("label", item.getDictValue());
webMap.put("id", item.getDictItemId().toString());
webMap.put("parentId", item.getDictItemId().toString());
dictItems.add(webMap);
itemsMap.put(item.getDictKey(), item.getDictValue());
}
redisHandle.set(Constants.REDIS_PREFIX_DIC + code, itemsMap);
redisHandle.set(Constants.REDIS_PREFIX_WEB_DIC + code, dictItems);
dictMaps.put(code, dictItems);
}
redisHandle.set(Constants.REDIS_PREFIX_WEB_DIC, dictMaps);
Date d = new Date();
//更新本号
String version = DateUtils.formatDate(d, "yyyyMMddHHmmss");
redisHandle.hset(RedisConstant.DIC_CACHE_VERSION_TABLE, RedisConstant.DIC_DICT_VERSION, version);
log.info("更新数据字典版本为:{}", version);
log.info("添加基础数据字典 结束 共计{}秒", (System.currentTimeMillis() - start) / 1000.0);
}
}

sy_dict与sp_dict——items表:

CREATE TABLE `sy_dict` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主码',
`dict_code` varchar(32) NOT NULL DEFAULT '' COMMENT '标识',
`company_id` int(11) DEFAULT '0' COMMENT '归属公司(0公用)',
`is_disabled` tinyint(4) DEFAULT '1' COMMENT '是否可删除编辑 0 不可删除编辑,1可删除编辑',
`description` varchar(100) DEFAULT '' COMMENT '字典描述',
`created_date` datetime DEFAULT NULL COMMENT '创建时间',
`created_by` int(11) DEFAULT NULL COMMENT '创建者',
`updated_date` datetime DEFAULT NULL COMMENT '更新人',
`updated_by` int(11) DEFAULT NULL COMMENT '更改人',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=213 DEFAULT CHARSET=utf8 COMMENT='数据字典表'; CREATE TABLE `sy_dict_items` (
`dict_item_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主码',
`dict_id` int(11) NOT NULL COMMENT '字典id',
`dict_key` varchar(32) DEFAULT '' COMMENT '键',
`dict_value` varchar(100) DEFAULT '' COMMENT '值',
`priority` int(11) DEFAULT '0' COMMENT '优先级',
`parent_id` int(11) DEFAULT NULL COMMENT '父子项目id',
PRIMARY KEY (`dict_item_id`),
KEY `fk_dictitem_dictid` (`dict_id`),
CONSTRAINT `sy_dict_items_ibfk_1` FOREIGN KEY (`dict_id`) REFERENCES `sy_dict` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1509 DEFAULT CHARSET=utf8 COMMENT='数据字典表';
												

Redis 在springBoot中的一个使用示例的更多相关文章

  1. redis在spring-boot中的应用

    Redis(REmote DIctionary Server) 是一个由Salvatore Sanfilippo写的key-value存储系统.Redis是一个开源的使用ANSI C语言编写.遵守BS ...

  2. redis(Springboot中封装整合redis,java程序如何操作redis的5种基本数据类型)

    平常测试redis操作命令,可能用的是cmd窗口 操作redis,记录一下 java程序操作reids, 操作redis的方法 可以用Jedis ,在springboot 提供了两种 方法操作 Red ...

  3. 《Entity Framework 6 Recipes》中文翻译系列 (20) -----第四章 ASP.NET MVC中使用实体框架之在MVC中构建一个CRUD示例

    翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 第四章  ASP.NET MVC中使用实体框架 ASP.NET是一个免费的Web框架 ...

  4. Struts2中的一个类型转换示例

    1.写一个属性文件,里面写好需要转换的类型数据,xwork-conversion.properties,解释: xwork-conversion.properties表示对所有action中的指定数据 ...

  5. redis基本操作和在springboot中的使用

    本文介绍redis的使用 redis启动步骤 说明 redis自增自减相关操作 redis string set操作 get操作 其他操作 redis hash set操作 get操作 其他操作 re ...

  6. (二)Redis在Mac下的安装与SpringBoot中的配置

    1 下载Redis 官网下载,下载 stable 版本,稳定版本. 2 本地安装 解压:tar zxvf redis-6.0.1.tar.gz 移动到: sudo mv redis-6.0.1 /us ...

  7. SpringBoot学习笔记(9)----SpringBoot中使用关系型数据库以及事务处理

    在实际的运用开发中,跟数据库之间的交互是必不可少的,SpringBoot也提供了两种跟数据库交互的方式. 1. 使用JdbcTemplate 在SpringBoot中提供了JdbcTemplate模板 ...

  8. Redis在springboot项目的使用

    一.在pom.xml配置redis依赖 <!-- redis客户端代码 --> <dependency> <groupId>org.springframework. ...

  9. 【*】Redis实战场景中相关问题

    一.Redis简介 redis主要解决的问题 分布式缓存是分布式系统中的重要组件,主要解决高并发.大数据场景下,热点数据访问的性能问题,提供高性能的数据快速访问. 使用缓存常见场景 项目中部分数据访问 ...

随机推荐

  1. c#利用三层架构做一个简单的登录窗体

    就个人而言,三层架构有点难理解,不知道该如何下手,各层与各层之间怎么调用 最近一直在研究三层架构,经过网上学习与多方打听写一下自己的心得.有不足之处,可以评论和私聊探讨 言归正传: 三层架构(3-ti ...

  2. Centos7设置文件夹写入权限

    用 root 账号执行chmod命令: #chmod -R 777 dirPath 参数 -R 表示递归,dirPath及其之内的所有文件夹.文件都被改变了权限. 例子: #chmod -R 777 ...

  3. windows下makefile命令详解

    转自https://blog.csdn.net/xiexievv/article/details/45775005 1. 如果已经有vc6的dsp工程,可直接导出nmake脚本文件(.mak) “Pr ...

  4. BZOJ 2763: [JLOI2011]飞行路线 【分层图模板】

    任意门:https://www.lydsy.com/JudgeOnline/problem.php?id=2763 2763: [JLOI2011]飞行路线 Time Limit: 10 Sec  M ...

  5. PHP设计模式——观察者模式

    PHP版本 <?php /** * 观察者模式 * 观察者模式能够便利的创建查看目标对象状态的对象,并且提供与核心对象非耦合的指定性功能. * * 为软件添加由某个动作或状态变化激活的,但是松散 ...

  6. mybatis学习记录六——一对一、一对多和多对多查询

    9       订单商品数据模型 9.1     数据模型分析思路 1.每张表记录的数据内容 分模块对每张表记录的内容进行熟悉,相当 于你学习系统 需求(功能)的过程. 2.每张表重要的字段设置 非空 ...

  7. Ajax去除缓存

    1.在Ajax发送请求钱加上anyAjaxObj.setRequestHeader("If-Modeified-Since","0").2.在Ajax发送请求钱 ...

  8. Android学习笔记_76_AsyncQueryHandler的应用

    研究AsyncQueryHandler这个类的时候遇到了几个重要的不清楚的知识点 1. Handler与Thread,Looper的关系 2. HandlerThread是干什么用的 3. Threa ...

  9. C#位数不足补零

    C#位数不足补零:int i=10;方法1:Console.WriteLine(i.ToString("D5"));方法2:Console.WriteLine(i.ToString ...

  10. How to Create a Basic Plugin

    Sometimes you want to make a piece of functionality available throughout your code. For example, per ...