SpringBoot+Redis data dictionary implementation

preface

In daily development, we use integer types to replace specific meanings of some fields, such as gender 0 for male and 1 for female. If it’s just some translation that doesn’t change, we can use constants or enumerated classes to implement it, but in fact we can also encounter situations where we might need to change, obviously it doesn’t make sense to use enumerated classes in this situation, so how do we dynamically translate?

The body of the

The data dictionary

A Data dictionary is a user-accessible directory that records database and application metadata. An active data dictionary is a data dictionary whose contents can be automatically updated by the DBMS when changes are made to the database or application structure. Passive data dictionaries are data dictionaries whose contents must be manually updated when modified.

We usually combine database to realize data dictionary, but in fact, data dictionary is often used, if frequent access to the database, will cause performance pressure on the database, in fact, we often use Redis to cache data dictionary to improve system performance.

Advantages of using Redis:

  1. The vast majority of requested operations are purely memory operations.
  2. Single thread mode is adopted to avoid unnecessary context switches and race conditions. Single thread here refers to the network request module only uses one thread (so there is no need to worry about concurrency safety), that is, one request handles all network requests, other modules still use multiple threads.
  3. Using dynamic strings (SDS), reserving certain space for strings to avoid performance loss caused by memory reallocation caused by string concatenation and interception.

SpringBoot+Redis data dictionary implementation

Rely on

<! --redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9. 0</version> </dependency> <! --lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.182.</version>
  <optional>true</optional>
</dependency>
Copy the code

The properties, application of the configuration class

#redis
spring.redis.host=127.0. 01.
spring.redis.port=6379
Copy the code

Dictionary table: SYS_DICT

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for SYS_DICT
-- ----------------------------
DROP TABLE IF EXISTS `SYS_DICT`;
CREATE TABLE `SYS_DICT` (
  `code` varchar(36) NOT NULL COMMENT 'primary key',
  `type_code` varchar(36) DEFAULT NULL COMMENT 'type code',
  `name` varchar(50) DEFAULT NULL COMMENT 'Display value',
  `value` int(20) DEFAULT NULL COMMENT 'Use value',
  `fixed` int(2) DEFAULT NULL COMMENT 'default 0 ',
  `creater` varchar(20) DEFAULT NULL COMMENT 'New person',
  `create_time` datetime DEFAULT NULL COMMENT 'New time',
  `updater` varchar(20) DEFAULT NULL COMMENT 'Editor',
  `update_time` datetime DEFAULT NULL COMMENT 'Edit time'.PRIMARY KEY (`code`),
  KEY `sys_type` (`type_code`),
  CONSTRAINT `sys_type` FOREIGN KEY (`type_code`) REFERENCES `SYS_DICT_TYPE` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


-- ----------------------------
-- Records of SYS_DICT
-- ----------------------------
INSERT INTO `SYS_DICT` VALUES ('182d4db6-aa50-11ea-aa1b-00163e08c9ed'.'9ed92c7e-aa4f-11ea-aa1b-00163e08c9ed'.'male'.'0'.'1'.null.null.null.null);
INSERT INTO `SYS_DICT` VALUES ('222cf983-aa50-11ea-aa1b-00163e08c9ed'.'9ed92c7e-aa4f-11ea-aa1b-00163e08c9ed'.'woman'.'1'.'1'.null.null.null.null);
Copy the code

Dictionary type table SYS_DICT_TYPE

SET FOREIGN_KEY_CHECKS=0;


-- ----------------------------
-- Table structure for SYS_DICT_TYPE
-- ----------------------------
DROP TABLE IF EXISTS `SYS_DICT_TYPE`;
CREATE TABLE `SYS_DICT_TYPE` (
  `code` varchar(36) NOT NULL,
  `name` varchar(50) DEFAULT NULL COMMENT 'For display',
  `value` varchar(50) DEFAULT NULL COMMENT 'Used for the preceding paragraph (to create a unique index)',
  `creater` varchar(20) DEFAULT NULL COMMENT 'New person',
  `create_time` datetime DEFAULT NULL COMMENT 'New time',
  `updater` varchar(20) DEFAULT NULL COMMENT 'Editor',
  `updater_time` datetime DEFAULT NULL COMMENT 'Edit time'.PRIMARY KEY (`code`),
  UNIQUE KEY `key_value` (`value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


-- ----------------------------
-- Records of SYS_DICT_TYPE
-- ----------------------------
INSERT INTO `SYS_DICT_TYPE` VALUES ('9ed92c7e-aa4f-11ea-aa1b-00163e08c9ed'.'gender'.'sex'.null.null.null.null);
Copy the code

RedisConfigurtion:RedisConfiguration class, resolvedRedisString format problem during data synchronization

@Configuration
public class RedisConfigurtion {
    @Autowired
    private RedisTemplate redisTemplate;
    @Bean
    public RedisTemplate<String, Object> stringSerializerRedisTemplate(a) {
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        returnredisTemplate; }}Copy the code

SpringUtil: Used for loadingSpringThe container

@Component
public class SpringUtil implements ApplicationContextAware {


    private static ApplicationContext applicationContext = null;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringUtil.applicationContext == null){ SpringUtil.applicationContext = applicationContext; }}/ / get the applicationContext
    public static ApplicationContext getApplicationContext(a) {
        return applicationContext;
    }


    // Get the Bean by name.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }


    // Get the Bean from class.
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    // Return the specified Bean by name and Clazz
    public static <T> T getBean(String name,Class<T> clazz){
        returngetApplicationContext().getBean(name, clazz); }}Copy the code

RedisDistUtil:SpringContainers are not allowed to be ordinaryPojocallService, you can manually pass the alarm in the following waySpringContainer loadBean.

public class RedisDistUtil {
    private static ApplicationContext context;
    /** * Convert code value *@param distname
     * @param value
     * @return
     * @throws Exception
     */
    public static String transformStr(String distname, int value)  {
        ApplicationContext context = SpringUtil.getApplicationContext();
        ISysDictService iSysDictService =context.getBean(ISysDictService.class);
        returniSysDictService.transformStr(distname,value); }}Copy the code

SysDictService

  • transformStrFrom:RedisGets the dictionary value from.
  • refreshCache: used to synchronize database data dictionary table data toRedisIn the.
@Transactional
@Service
@Slf4j
public class SysDictService implements ISysDictService {

    @Autowired
    SysDictPojoMapper sysDictPojoMapper;

    @Autowired
    RedisTemplate redisTemplate;

    /** * Convert code value **@param distname
     * @param value
     * @return
     * @throws Exception
     */
    @Override
    public String transformStr(String distname, int value) {
        return redisTemplate.opsForValue().get(distname + "_"+ value) ! =null ?
               redisTemplate.opsForValue().get(distname + "_" + value).toString() : String.valueOf(value);
    }

    /** * Refresh the cache */
    @Override
    public void refreshCache(a) {
        log.info("Start refresh code table cache");
        List<SysDictPojo> sysDictPojoList = sysDictPojoMapper.getall();
        long startTime = System.currentTimeMillis();
        for (SysDictPojo sysDictPojo : sysDictPojoList) {
            redisTemplate.opsForValue().set(sysDictPojo.getTypeCodeValue() + "_" + sysDictPojo.getValue(), sysDictPojo.getName());
        }
        long endTime = System.currentTimeMillis();
        log.info("End refresh code table cache, total:" + sysDictPojoList.size() + "Bar, time:" + (endTime - startTime) + "毫秒"); }}Copy the code

SysDictPojo: Entity class of data dictionary

@Setter
@Getter
@ToString
public class SysDictPojo implements Serializable {


    private static final long serialVersionUID = 7845051152365224116L;
    private String code;


    private String typeCode;


    private String typeCodeValue;


    private String name;


    private Integer value;


    private Integer fixed;


    private String creater;


    private Date createTime;


    private String updater;


    private Date updateTime;

}
Copy the code

Getall: Queries all data dictionary values of the database

<select id="getall" resultType="com.luo.dao.entity.SysDictPojo">
  select
  t1.name,
  t1.value,
  t2.value typeCodeValue
  from SYS_DICT t1
  left join SYS_DICT_TYPE t2 on t2.code =t1.type_code
</select>
Copy the code

validation

UserPojoRes:getMethod to replace the data dictionary values

@Setter
@Getter
@ToString
public class UserPojoRes implements Serializable {
    private static final long serialVersionUID = -2145503717390503506L;

    /** * primary key */
    private String id;
    /** * name */
    private String name;


    /** ** gender */
    private int sex;


    /** ** Gender display */
    private String sexStr;


    /** * message */
    private String msg;


    public String getSexStr(a) {
        return RedisDistUtils.transformStr("sex".this.sex); }}Copy the code

Access the analog interface and query user information based on id:

\