在现系统中使用了一个字典表,更新或插入字典表需要做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. VBA注意事项

    以下是项目过程中遇到的坑,可能有些说明的部分不一定严谨,仅供参考 1.最好保存成 [*.xlsm]文件 2.注意 VBA 的参数类型,使用的参数如果未声明直接使用的话会出现类型不匹配的错误 3.代码写 ...

  2. 对 Canal (增量数据订阅与消费)的理解

    概述 canal是阿里巴巴旗下的一款开源项目,纯Java开发.基于数据库增量日志解析,提供增量数据订阅&消费,目前主要支持了MySQL(也支持mariaDB). 起源:早期,阿里巴巴B2B公司 ...

  3. mysqlimport导入简单测试

    1    创建一个文本文档:[mysql@xxxycrdb]$ more /tmp/ldcmd1.txt 1,abc,abc@qq.com1,abc,abc@qq.com1,abc,abc@qq.co ...

  4. June 16th 2017 Week 24th Friday

    Progress is the activity of today and the assurance of tomorrow. 进步是今天的活动,明天的保证. The best preparatio ...

  5. June 04th 2017 Week 23rd Sunday

    It is not the mountain we conquer but outselves. 我们要征服的不是高山,而是我们自己. After days of hard working, I sl ...

  6. CentOS 6.4安装谷歌浏览器(chromium)不是chrome

    原文转载于http://www.wypblog.com/archives/782 今天给大家介绍如何在CentOS 6.4平台上面安装chromium浏览器,和Google的Chrome也类似,虽然不 ...

  7. 2016 ACM/ICPC亚洲区大连站 F - Detachment 【维护前缀积、前缀和、二分搜索优化】

    F - Detachment In a highly developed alien society, the habitats are almost infinite dimensional spa ...

  8. HTML5之转动的轮子

    <!doctype html><html> <head></head> <body> <canvas width="1000 ...

  9. 【办公-Word-VB】人民币大写转换-带完整注释

    完整代码见:我的CSDN博客 -------------------- 应公司财务人员的请求,需在Word中做个:输入阿拉伯数字,自动转换成大写,并填充到Word控件中对应的亿.万.千控件格子的功能, ...

  10. ListItem Updating事件监视有没有上传附件

    using System; using System.Collections.Generic; using System.Text; using Microsoft.SharePoint; using ...