在现系统中使用了一个字典表,更新或插入字典表需要做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#MD5加密解密

    MD5的全称是Message-Digest Algorithm 5(信息-摘要算法),在90年代初由MIT Laboratory for Computer Science和RSA Data Secur ...

  2. 【Spring实战】—— 15 Spring JDBC模板使用

    前一篇通过对传统的JDBC的使用操作,可以体会到使用的繁琐与复杂,套句话说,是用了20%作了真正的工作,80%作了重复的工作. 那么通过本篇,可以了解如下的内容: 1 如何配置数据源 2 如何在spr ...

  3. xtrabackup 备份恢复

    XtraBackup物理备份 Percona XtraBackup是世界上唯一的开源,免费的MySQL热备份软件,为InnoDB和XtraDB 数据库执行非阻塞备份.使用Percona XtraBac ...

  4. userdel

    功能说明:用于删除指定的用户及该用户相关的文件. 参数选项:-f 强制删除用户,即使用户当前已登录.-r 删除用户的同时,删除与用户相关的所有文件. 说明:尽量不要用userdel删除用户,而是采用在 ...

  5. 2019.03.19 ZJOI2019模拟赛 解题报告

    得分: \(100+10+45=155\)(\(T1\)又是水题,\(T2\)写暴力,\(T3\)大力\(STL\)乱搞) \(T1\):哈夫曼树 首先,根据题目中给出的式子,可以发现,我们要求的其实 ...

  6. HDU 3336 KMP

    题意:求每一个前缀,跟前缀相同的每个子串. 此题:网上很多都是假程序,不过也AC了,的确我测试几个案例之后的的确确是存在这个问题. 分析:每一个前缀,可以考虑KMP,f失配指针,如何求得它出现了多少次 ...

  7. CSU 1974

    Description 对于csuxushu来说,能够在CSU(California State University)组织2017年的ACM暑期集训让他感到十分荣幸. csuxushu是一名充满梦想 ...

  8. POJ Treasure Exploration 【DAG交叉最小路径覆盖】

    传送门:http://poj.org/problem?id=2594 Treasure Exploration Time Limit: 6000MS   Memory Limit: 65536K To ...

  9. 【转】Mac本地生成SSH Key 的方法

    1. 查看秘钥是否存在 打开终端查看是否已经存在SSH密钥:cd ~/.ssh 如果没有密钥则不会有此文件夹,有则备份删除,   也可以直接删除, 2.生成新的秘钥, 命令如下 $ssh-keygen ...

  10. Django学习之ORM操作

    一.一般操作 二.必知必会13条 返回QuerySet对象的方法有 特殊的QuerySet 返回具体对象的 返回布尔值的方法有 返回数字的方法 三.单表查询之神奇的双下划线 四.ForeignKey操 ...