参考博客1
参考博客2
springboot+redis+mybatis实现数据字典功能Hash底层存储数据的方式确实跟其他数据结构有点不同,其他数据结构几乎都是:Key-Value的存储,而Hash则是:Key – [Field-Value] 的存储,也就是说其他数据结构的Value一般是确切的值,而Hash的Value是一系列的键值对。
通常我们是这样称呼Hash的存储的:大Key为实际的Key,小Key为Field,而具体的取值为Field对应的值value
实践:系统数据字典实时触发缓存存储
@Autowired private RedisTemplateredisTemplate;
修改为:
@Resource private RedisTemplate2.1.2 redis存储乱码redisTemplate;
问题如下图
如下配置解决该问题
@Bean
public RedisTemplate redisTemplate(RedisTemplate redisTemplate) {
StringRedisSerializer stringSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer
2.2 在数据库建立 系统字典 表 sys_dict_config
CREATE TABLE `sys_dict_config` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`module` varchar(100) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '模块',
`type` varchar(100) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '字典类型',
`name` varchar(100) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '字典名称',
`code` varchar(100) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '选项编码',
`value` varchar(100) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '选项取值',
`order_by` int(11) DEFAULT '1' COMMENT '排序',
`is_active` int(11) DEFAULT '1' COMMENT '是否有效(1=是;0=否)',
`create_time` timestamp NULL DEFAULT NULL ON UPDATe CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_type_code` (`type`,`code`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.3 新建实体类 SysDictConfig,SysDictConfigMapper,SysDictConfigMapper.xml,代码如下:SysDictConfig: BaseResponse.java
package com.bridge.common; public class BaseResponseRedisConfig.java{ private String code; private String msg; private T data; public BaseResponse(String code) { this.code = code; } public BaseResponse(String code, String msg) { this.code = code; this.msg = msg; } public BaseResponse(String code, String msg, T data) { this.code = code; this.msg = msg; this.data = data; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
package com.bridge.config;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.reflect.Method;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@Bean
public RedisTemplate redisTemplate(RedisTemplate redisTemplate) {
// RedisTemplate redisTemplate = new RedisTemplate<>();
StringRedisSerializer stringSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer
ErrorCodeEnum.java
package com.bridge.enums;
public enum ErrorCodeEnum {
SUCCESS("SUCCESS","成功"),
FAIL("FAIL","失败"),
;
private String code;
private String msg;
ErrorCodeEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
SysDictConfigMapper.java
package com.bridge.mapper;
import com.bridge.model.SysDictConfig;
import java.util.List;
public interface SysDictConfigMapper {
int deleteByPrimaryKey(Integer id);
int insert(SysDictConfig sysDictConfig);
int insertSelective(SysDictConfig sysDictConfig);
SysDictConfig selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(SysDictConfig sysDictConfig);
int updateByPrimaryKey(SysDictConfig sysDictConfig);
List selectActiveConfigs();
List selectListByType(String type);
}
SysDictConfig.java
package com.bridge.model;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
import java.util.Date;
public class SysDictConfig implements Serializable {
private Integer id;
@NotBlank(message = "字典类型不能为空")
private String type;
@NotBlank(message = "模块不能为空")
private String module;
@NotBlank(message = "字典名称不能为空")
private String name;
@NotBlank(message = "选项编码不能为空")
private String code;
@NotBlank(message = "选项取值不能为空")
private String value;
//排序
private Integer orderBy;
//是否有效(1=是;0=否)
private Byte isActive=1;
//创建时间
private Date createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Integer getOrderBy() {
return orderBy;
}
public void setOrderBy(Integer orderBy) {
this.orderBy = orderBy;
}
public Byte getIsActive() {
return isActive;
}
public void setIsActive(Byte isActive) {
this.isActive = isActive;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
service和impl
1 service
package com.bridge.service;
import com.bridge.model.SysDictConfig;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
public interface IRedisHashService {
@Transactional(rollbackFor = Exception.class)
Integer addSysDictConfig(SysDictConfig config) throws Exception;
Map> getSysDictConfig() throws Exception;
List getByType(String type) throws Exception;
Map> getAllCacheConfig();
List getCacheConfigByType(String type);
List update(String type);
}
// impl
package com.bridge.service.impl;
import com.bridge.mapper.SysDictConfigMapper;
import com.bridge.model.SysDictConfig;
import com.bridge.service.IRedisHashService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
@Service
public class RedisHashServiceImpl implements IRedisHashService {
private static final Logger log = LoggerFactory.getLogger(RedisHashServiceImpl.class);
private static final String RedisHashKey = "Redis:Hash";
@Resource
private SysDictConfigMapper sysDictConfigMapper;
@Resource
private RedisTemplate redisTemplate;
@Override
@Transactional(rollbackFor = Exception.class)
public Integer addSysDictConfig(SysDictConfig config) throws Exception {
int res = sysDictConfigMapper.insertSelective(config);
if (res > 0) {
//实时触发数据字典的hash存储
cacheConfigMap();
}
return config.getId();
}
@Override
public Map> getSysDictConfig() throws Exception {
return getAllCacheConfig();
}
@Override
public List getByType(final String type) throws Exception {
return getCacheConfigByType(type);
}
@Async
public void cacheConfigMap() {
try {
List sysDictConfigList = sysDictConfigMapper.selectActiveConfigs();
if (sysDictConfigList != null && !sysDictConfigList.isEmpty()) {
Map> dataMap = Maps.newHashMap();
//所有的数据字典列表遍历 -> 转化为 hash存储的map
sysDictConfigList.forEach(sysDictConfig -> {
List list = dataMap.get(sysDictConfig.getType());
if (CollectionUtils.isEmpty(list)) {
list = Lists.newLinkedList();
}
list.add(sysDictConfig);
dataMap.put(sysDictConfig.getType(), list);
});
//存储到缓存hash中
HashOperations> hashOperations = redisTemplate.opsForHash();
hashOperations.putAll(RedisHashKey, dataMap);
}
} catch (Exception e) {
log.error("实时获取所有有效的数据字典列表-转化为map-存入hash缓存中-发生异常:", e.fillInStackTrace());
}
}
@Async
public void cacheConfigMap(String type) {
try {
List sysDictConfigList = sysDictConfigMapper.selectListByType(type);
if (CollectionUtils.isEmpty(sysDictConfigList)) {
return;
}
Map> dataMap = Maps.newHashMap();
dataMap.put(type, sysDictConfigList);
//存储到缓存hash中
HashOperations> hashOperations = redisTemplate.opsForHash();
hashOperations.putAll(RedisHashKey, dataMap);
} catch (Exception e) {
log.error("实时获取所有有效的数据字典列表-转化为map-存入hash缓存中-发生异常:", e.fillInStackTrace());
}
}
@Override
public Map> getAllCacheConfig() {
Map> map = Maps.newHashMap();
try {
HashOperations> hashOperations = redisTemplate.opsForHash();
map = hashOperations.entries(RedisHashKey);
} catch (Exception e) {
log.error("从缓存hash中获取所有的数据字典配置map-发生异常:", e.fillInStackTrace());
}
return map;
}
@Override
public List getCacheConfigByType(final String type) {
List list = Lists.newArrayList();
try {
HashOperations> hashOperations = redisTemplate.opsForHash();
list = hashOperations.get(RedisHashKey, type);
} catch (Exception e) {
log.error("从缓存hash中获取特定的数据字典列表-发生异常:", e.fillInStackTrace());
}
// 缓存数据
if (CollectionUtils.isEmpty(list)) {
cacheConfigMap();
}
return list;
}
@Override
public List update(String type) {
cacheConfigMap(type);
return getCacheConfigByType(type);
}
}
SysDictConfigMapper.xml
id, module,type, name, code, value, order_by, is_active, create_time



