Springboot integrated redis process

Time:2022-8-3

Redis introduction: redis service

Redis (replicate dictionary server) is a project completed by Salvatore Sanfilippokey-valueStorage system is a cross platform non relational database.

Redis is an open source key value pair storage database written in ANSI C language, following BSD protocol, supporting network, memory based, distributed, and selectable persistence, and provides a multilingual API.

Redis is usually regarded as a data structure server, and its values can be strings, hashes, lists, collections, and ordered collections.

Redis advantages

Unusually fast, which can perform about 110000 write (set) operations per second

It can perform about 81000 read (get) operations per second

Support rich data structures

Operation is atomic, all redis operations are atomic operations, which ensures that two clients can access concurrently, and the redis server can receive updated values.

Multi use tools, cache, message queue (redis supports publish / subscribe locally), any short-term data in the application.

Redis installation

Download address:

https://github.com/MSOpenTech/redis/releases

Redis supports 32-bit and 64 bit. After downloading and decompressing, the folder contains many sub files. Open the CMD window, switch it to the redis directory, and enter the name:

D:\sdk\Redis-x64-5.0.9  redis-server.exe  redis.windows.conf

What is redis

Redis is one of the most popular NoSQL databases. Redis is an open-source key value pair storage database written in ANSI C, which contains a variety of data structures, supports network, is memory based, and has optional persistence. It has the following characteristics:

  • Memory based operation, high performance
  • It supports distribution and can be expanded infinitely in theory
  • Key value storage system
  • Open source, ANSI C language, BSD protocol compliance, network support, memory based and persistent log type, key value database, and multi language API

Compared with other database types, redis has the following characteristics:

  • C/s communication model
  • Single process and single thread model
  • Rich data types
  • Operation is atomic
  • Persistence
  • High concurrent read and write
  • Support Lua scripts

If you want to make it easier to start using redis, you can add the redis installation path to the environment variable by clicking redis server Exe to start the redis service.

Springboot integrated redis process

1. In pom Configuring dependent jars in XML


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

2. Configure the core file in springboot

In application Add redis configuration information under the properties file

#Configure redis
spring.redis.host:localhost
spring.redis.password=
spring.redis.port=6379

3. Redis configuration class and its use

Redis configuration class

//Redisconfig redisconfig configuration
@Configuration
public class RedisConfig {
    /**
     * key redis serializer: {@link StringRedisSerializer} and
     * key redis serializer: {@link Jackson2JsonRedisSerializer}
     **/
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        //Create object
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        Jackson2JsonRedisSerializer valueRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //Set the value of redis to JSON format and store the serialization type of object information
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        valueRedisSerializer.setObjectMapper(objectMapper);
​
        //Create a keyredisserializer
        RedisSerializer keyRedisSerializer = new StringRedisSerializer();
        //Setting information
        template.setKeySerializer(keyRedisSerializer);
        template.setValueSerializer(valueRedisSerializer);
        template.setHashKeySerializer(keyRedisSerializer);
        template.setHashValueSerializer(valueRedisSerializer);
        template.setConnectionFactory(factory);
        template.afterPropertiesSet();
        return template;
    }
​
    //Redisutils() method
    @Bean
    public RedisUtils redisUtils(@Autowired RedisTemplate redisTemplate) {
        return new RedisUtils(redisTemplate);
    }
}

Redis tool classFirst, redis’s operations such as adding, deleting, modifying, and querying are targeted at data of various data types

/**
 *Redis tool class
 *
 * @author Jone
 */
// RedisUtils
@Slf4j
public class RedisUtils {
​
    //Initialize variables
    private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);
​
​
    private static RedisTemplate redisTemplate;
​
    public RedisUtils(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
​
    // =============================common============================
​
​
    /**
     *Determine whether the key exists
     *
     *@param key
     *@return true exists false does not exist
     */
    public Boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            logger. Error ("judge whether the key has an exception: {}", e);
            return false;
        }
    }
​
    /**
     *Normal cache fetch
     *
     *@param key
     *@return value
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
​
    /**
     *Delete
     * @param key
     * @return
     */
    public boolean del(String ... key){
        if(key!=null&&key.length>0){
​
                redisTemplate.delete(key[0]);
                return true;
            }else{
                redisTemplate.delete(CollectionUtils.arrayToList(key));
                return true;
            }
        }
        return false;
    }
​
    // SET JIHE
    public Set getKeys(){
       return redisTemplate.keys("*");
    }
​
    /**
     *Normal cache put
     *
     *@param key
     *@param value value
     *@return true success false failure
     */
    public Boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            logger. Error ("set exception: {}", e);
            return false;
        }
    }
}

After the configuration is complete, redistemplate is automatically configured, and redisteplate needs to be injected into the class that operates redis, as shown below:

//Using redistemplate                                                                                
@Autowired
private RedisTemplate<String, String> redisTemplate;
​
@Autowired 
private RedisTemplate<Object, Object> redisTemplate;

The above is the details of the process of integrating redis with springboot. For more information about the actual combat of springboot redis, please pay attention to other relevant articles of developeppaer!