Spring Boot2 (C): Use Spring Boot2 integrated Redis cache

Foreword

In front of a summary of the caching mechanism SpringBoot achieve Mybatis of , but rarely used in actual project Mybatis secondary cache mechanism, but rather to use more third-party caching Redis .

Redis is an open source written in ANSI C, support network, based on memory, optional persistent key-value pairs stored in the database.

Installation start Redis

Installation of Redis do not speak too much, go directly to the official download redis , download Redis-x64-3.2.100.zip , cmd, enter redis in directory: redis-server.exe redis.windows.conf to start

Further tools may be connected to desktop client Redis visualization: redisdesktop

Code deployment

Spring Boot quickly build project

Add redis dependence

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.yml Configuration

spring:
  redis:
    host: 127.0.0.1
    database: 0
    password:
    port: 6379
    jedis:
      pool:
        max-active: 1000  # 连接池最大连接数(使用负值表示没有限制)
        max-wait: -1ms  # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 10  # 连接池中的最大空闲连接
        min-idle: 5 # 连接池中的最小空闲连接

RedisConfig configuration class

@Autowired
private RedisConnectionFactory factory;

/**
 *
 * @return
 */
@Bean
public RedisTemplate<String, Object> redisTemplate() {
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    //更改在redis里面查看key编码问题
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashValueSerializer(new StringRedisSerializer());
    redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
    redisTemplate.setConnectionFactory(factory);
    return redisTemplate;
}

RedisUtils Tools

@Autowired
private RedisTemplate redisTemplate;
// 简单的K-V操作
@Resource(name="redisTemplate")
private ValueOperations<String, String> valueOperations;

// 针对Map类型的数据操作
@Resource(name="redisTemplate")
private HashOperations<String, String, Object> hashOperations;

// 针对List类型的数据操作
@Resource(name="redisTemplate")
private ListOperations<String, Object> listOperations;

// set类型数据操作
@Resource(name="redisTemplate")
private SetOperations<String, Object> setOperations;

// zset类型数据操作
@Resource(name="redisTemplate")
private ZSetOperations<String, Object> zSetOperations;

Entity class SysCodeEntity

@Data
public class SysCodeEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    private int id;

    // 分类编码
    private String kindCode;

    // 分类名称
    private String kindName;

    // CODE编码
    private String code;
    ......
}

ServiceImpl implementation class

/**
 * 查询所有数字字典
 * @return
 */
@Override
public List<SysCodeEntity> queryCodeAll() {
    logger.info("先从缓存中查找,如果没有则去数据进行查询");
    List<SysCodeEntity> codeList = (List<SysCodeEntity>)redisTemplate.opsForList().leftPop("codeList");
    if (codeList == null) {
        logger.info("说明缓存中没有数据,则到数据库中查询");
        codeList = sysCodeDao.queryCodeAll();

        logger.info("将数据库获取的数据存入缓存");
        redisTemplate.opsForList().leftPush("codeList", codeList);
    } else {
        logger.info("则说明缓存中存在,直接从缓存中获取数据");
    }
    logger.info("codeList=" + codeList);
    return codeList;
}

The above examples specifically explained in the notes have been reflected by the leftPop opsForList acquired and stored and leftPush Redis cached data.

Controller layer implementation

/**
 * 查询所有数字字典
 * @return
 */
@RequestMapping("/getAll")
private List<SysCodeEntity> getUser() {
    Long startTime = System.currentTimeMillis(); //开始时间
    List<SysCodeEntity> codeList = sysCodeService.queryCodeAll();
    Long endTime = System.currentTimeMillis(); //结束时间
    System.out.println("查询数据库--共耗时:" + (endTime - startTime) + "毫秒"); //1007毫秒
    return codeList;
}

Postman test

http://localhost:8080/getAll

Log information

Summary and expansion

1, Redis support: string String, Hash Hash, List List, a collection of Set, ordered set Sorted Set, publish and subscribe Pub / Sub, transactions Transactions, 7 data types

2, Redis practical scenario: caching system, counter, message queue system, leaderboards and related issues, social networks, according to user voting and sorting time, expired item processing, real-time systems

3, Redis advanced features: slow query (internal execution time exceeds a specified time limit queries), PipeLine pipeline (client and redis reduce the number of communications for batch processing), BitMap bitmap (designed for large amounts of data), HyperLogLog (a very small space to complete independent statistics), publish-subscribe, message queues, GEO location storage

4, Redis persistence:

Snapshot RDB (using a snapshot , a semi-durable mode data set from time to time into the hard disk from memory format to RDB asynchronously)

Log AOF (1.1 version began to use safer alternatives AOF format, log type that can only append. The data modification operations set up .Redis record can only make changes to the additional log records in the background to avoid infinite growth )

5, Redis distributed solution: master-slave replication, clustering ...

Sample Code -github

Late continuing to explore technology Redis To be continued ...

Recommended reading: Getting to Redis distributed practice


About the Author:

Personal blog: birds do not shit

github Home: niaobulashi

github blog: birds do not shit

Nuggets: birds do not shit

Park blog: birds do not shit

Know almost: birds do not shit

Guess you like

Origin www.cnblogs.com/niaobulashi/p/spring-boot-redis.html