在现系统中使用了一个字典表,更新或插入字典表需要做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. Python新式类 单例模式与作用域(四)

    1 新式类与旧式类 新式类拥有经典类的全部特性之外,还有一些新的特性,比如 __init__发生变化,新增了静态方法__new__,python3目前都采用新式类,新式类是广度优先,旧式类是深度优先 ...

  2. 收放卷及张力控制 PID调试技巧

    1) 小 Kp( 0.01) , 大 Ti ( 20000ms) 2)逐渐增大Kp, 减小Ti ( 20000ms – 3000ms),避免发生震荡 3)观察I-out 是否在0附近 可能原因:卷径不 ...

  3. June 14th 2017 Week 24th Wednesday

    Love looks not with the eyes, but with the mind. 爱,不在眼里,而在心中. Staring in her eyes and you will find ...

  4. 描边时消除锯齿SetSmoothingMode

    SmoothingModeAntiAlias 指定消除锯齿的呈现. SmoothingModeDefault 指定默认模式. SmoothingModeHighQuality 指定高质量.低速度呈现. ...

  5. 如何用ABAP代码读取CDS view association的数据

    我有如下一个CDS view, 这个view的数据来自CRMD_ORDERADM_H, 定义了一个名称为_statushelp的association, 指向了另一个CDS view Z_C_Stat ...

  6. 【[SDOI2009]晨跑】

    板子 题意就是每个点只能经过一次 所以非常显然拆点,除去\(1,n\)每个点\(i\)向\(i'\)连一条容量为\(1\)费用为\(0\)的边 剩下的边按照输入给出的建就好了 代码 #include& ...

  7. 2014-2015 ACM-ICPC East Central North America Regional Contest (ECNA 2014) A、Continued Fractions 【模拟连分数】

    任意门:http://codeforces.com/gym/100641/attachments Con + tin/(ued + Frac/tions) Time Limit: 3000/1000 ...

  8. 0.Python 爬虫之Scrapy入门实践指南(Scrapy基础知识)

    目录 0.0.Scrapy基础 0.1.Scrapy 框架图 0.2.Scrapy主要包括了以下组件: 0.3.Scrapy简单示例如下: 0.4.Scrapy运行流程如下: 0.5.还有什么? 0. ...

  9. Markdown黑色背景代码高亮

    因为我默认的不是Markdown...这里分享给用Markdown的小伙伴吧. /* 使用了Monokai Sublime的黑色主题皮肤,但是还存在样式冲突,需要自己修改 这个样式只适合使用maked ...

  10. 几个常用的 Git 高级命令

    Git 是一款开源优秀的版本管理工具,它最初由 Linus Torvalds 等人开发,用于管理 Linux Kernel 的版本研发.相关的书籍和教程网上琳琅满目,它们多数都详细的介绍其基本的使用和 ...