Replacing hashmap perfectly, SpringBoot integrates Redis cache DB data

1, Baidu Encyclopedia

Redis is a key value storage system. Similar to memcached, it supports relatively more stored value types, including string (string), list (linked list), set (set), zset(sorted set -- ordered set) and hash (hash type). These data types support push/pop, add/remove, intersection, union, difference and richer operations, and these operations are atomic. On this basis, redis supports various sorting methods. Like memcached, data is cached in memory to ensure efficiency. The difference is that redis periodically writes the updated data to the disk or writes the modification operation to the additional record file, and realizes master-slave synchronization on this basis.

Redis is a high-performance key value database. The emergence of redis largely compensates for the shortage of key/value storage such as memcached, and can play a good supplementary role to relational databases on some occasions. It provides Java, C/C + +, c#, PHP, JavaScript, Perl, Object-C, Python, Ruby, Erlang and other clients, which is very convenient to use.

Redis supports master-slave synchronization. Data can be synchronized from the master server to any number of slave servers, and the slave server can be the master server associated with other slave servers. This enables redis to perform single-layer tree replication. Save disk can write data intentionally or unintentionally. Because the publish / subscribe mechanism is fully implemented, when the slave database synchronizes the tree anywhere, it can subscribe to a channel and receive the complete message publishing records of the master server. Synchronization is very helpful for the scalability of read operations and data redundancy.

2, Redis Download

3, Installing Redis in Linux

1. Upload and unzip

Redis is generally installed in the Linux environment. Start the virtual machine, upload the redis compressed package to the Linux server through xftp, and decompress it.

2. Modify redis Conf configuration file to enable it to start in the background

4, Java calls redis

1. Import pom

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.2.0</version>
</dependency>

2. Writing Java main methods

Call the ping method in Redis, and an exception occurs:

(1) At first, I thought it was a firewall problem. Later, I found that the IP address was wrong by checking the redis status. It should not be 127.0.0.1

(2) Modify redis conf

Note: it should be noted that you are modifying redis When conf, ① note bind 127.0.0.1; ② The native access protection mode needs to be set to no

3. Execute the main method again, and the execution is successful!

5, Code examples of five data types

package com.guor.redis;
 
import redis.clients.jedis.Jedis;
 
import java.util.List;
import java.util.Set;
 
public class JedisTest01 {
    public static void main(String[] args) {
        test05();
    }
 
    private static void test01(){
        Jedis jedis = new Jedis("192.168.194.131", 6379);
        String value = jedis.ping();
        System.out.println(value);
        //add to
        jedis.set("name","GooReey");
        //obtain
        String name = jedis.get("name");
        System.out.println(name);
 
        jedis.set("age","30");
        jedis.set("city","dalian");
        //Get all key s
        Set<String> keys = jedis.keys("*");
        for(String key : keys){
            System.out.println(key+" --> "+jedis.get(key));
        }
 
        //Add multiple key s and value s
        jedis.mset("name1","zs","name2","ls","name3","ww");
        List<String> mget = jedis.mget("name1", "name2");
        System.out.println(mget);//[zs, ls]
    }
 
    //list
    private static void test02(){
        Jedis jedis = new Jedis("192.168.194.131", 6379);
        jedis.lpush("key1","01","02","03");
        List<String> values = jedis.lrange("key1",0,-1);
        System.out.println(values);//[03, 02, 01]
    }
 
    //set
    private static void test03(){
        Jedis jedis = new Jedis("192.168.194.131", 6379);
        jedis.sadd("username","zs","ls","ww");
        Set<String> names = jedis.smembers("username");
        System.out.println(names);//[ww, zs, ls]
    }
 
    //hash
    private static void test04(){
        Jedis jedis = new Jedis("192.168.194.131", 6379);
        jedis.hset("users","age", "20");
        String hget = jedis.hget("users","age");
        System.out.println(hget);
    }
 
    //zset
    private static void test05(){
        Jedis jedis = new Jedis("192.168.194.131", 6379);
        jedis.zadd("china",100d,"shanghai");
        Set<String> names = jedis.zrange("china",0,-1);
        System.out.println(names);//[shanghai]
    }
}

6, Mobile phone verification code function code example

package com.guor.redis;
 
import redis.clients.jedis.Jedis;
 
import java.util.Random;
 
public class PhoneCode {
    public static void main(String[] args) {
        verifyCode("10086");//795258
        getRedisCode("10086","795258");//success.
    }
 
    //1. Generate 6-digit verification code
    public static String getCode(){
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            int rand = random.nextInt(10);
            code += rand;
        }
        return code;//849130
    }
 
    //2. Each mobile phone can only send three times a day. Put the verification code in redis and set the expiration time
    public static void verifyCode(String phone){
        Jedis jedis = new Jedis("192.168.194.131", 6379);
        //Splice key
        //Number of times sent by mobile phone key
        String countKey = "VerifyCode" + phone + ":count";
        //Verification code key
        String codeKey = "VerifyCode" + phone + ":code";
        //Each phone can only send three times a day
        String count = jedis.get(countKey);
        if(count == null){
            //Set expiration time
            jedis.setex(countKey,24*60*60,"1");
        }else if(Integer.parseInt(count)<=2){
            //Sending times + 1
            jedis.incr(countKey);
        }else if(Integer.parseInt(count)>2){
            System.out.println("More than three times have been sent today");
            jedis.close();
        }
 
        String vCode = getCode();
        jedis.setex(codeKey,120,vCode);
        jedis.close();
    }
 
    //3. Verification code verification
    public static void getRedisCode(String phone, String code){
        //Get the verification code from redis
        Jedis jedis = new Jedis("192.168.194.131", 6379);
        //Verification code key
        String codeKey = "VerifyCode" + phone + ":code";
        String redisCode = jedis.get(codeKey);
        if(redisCode.equals(code)){
            System.out.println("success.");
        }else{
            System.out.println("error");
        }
        jedis.close();
    }
}


When more than three times:

7, Spring boot integrates Redis

1. Construction, introduction of pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.guor</groupId>
    <artifactId>redisspringboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>redisspringboot</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.4.5</version>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.9.0</version>
        </dependency>
 
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>

2. Configuration class

(1)application.properties

# Redis database index (0 by default)
spring.redis.database=0
# Redis server address
spring.redis.host=192.168.194.131
# Redis server connection port
spring.redis.port=6379
# Redis server connection password (blank by default)
spring.redis.password=
# Maximum number of connections in the connection pool (negative value indicates no limit)
spring.redis.jedis.pool.max-active=20
# Maximum blocking wait time of connection pool (negative value indicates no limit)
spring.redis.jedis.pool.max-wait=-1
# Maximum free connections in the connection pool
spring.redis.jedis.pool.max-idle=10
# Minimum free connections in connection pool
spring.redis.jedis.pool.min-idle=0
# Connection timeout (MS)
spring.redis.timeout=1000

(2)RedisConfig

package com.guor.redisspringboot.config;
 
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
 
import java.time.Duration;
 
@EnableCaching
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
 
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        jackson2JsonRedisSerializer.setObjectMapper(om);
 
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // The key is serialized by String
        template.setKeySerializer(stringRedisSerializer);
        // The key of hash is also serialized by String
        template.setHashKeySerializer(stringRedisSerializer);
        // value is serialized by jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // The value serialization method of hash is jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
 
    /**
     * Customized configuration of RedisCacheManager based on SpringBoot2
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //Initialize a RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        //Set the value serialization mode of CacheManager to json serialization
        RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
        RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer);
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
 
        //Set the default expiration period to 1 day
        defaultCacheConfig.entryTtl(Duration.ofDays(1));
        //Initialize RedisCacheManager
        return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
    }
}

3. Control class test

package com.guor.redisspringboot.controller;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @GetMapping
    public String getRedis(){
        redisTemplate.opsForValue().set("name","zs");
        String name = (String) redisTemplate.opsForValue().get("name");
        return name;
    }
}

Keywords: Java Redis Spring Boot

Added by akillez on Mon, 10 Jan 2022 01:25:59 +0200