Two basic ways of configuring redis with springboot

When building the springboot+Redis environment based on IDEA, deeply understand the relevant mechanisms of the springboot framework, know when to use the configuration file and when to use the annotation, and summarize the relevant core issues as clearly and completely as possible.

Don't talk much. Get into the subject.

1. There are two ways to build springboot+redis, which are as follows:

Method 1: Based on the redistemplate class, redistemplate is a redis management tool provided by springdate. springboot can be injected directly.

Dependency needs to be installed:

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

Method 2: Based on jedis, jedis is a Java oriented Redis client officially recommended by Redis. Jedis can be called directly without injection. If you want to inject into spring, you need to create a jedis configuration file. The function of the configuration file is to inject jedis when the project is started, and then we can get the information of JedisPool class in other classes.

Dependencies to install:

<!-- redis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

The method adopted in this project is based on method 2, which is conducive to jedis. jedisPool class information is injected by creating jedis configuration file.

2. The project structure is as follows:

 

 

 

3. From the normal start of the project, explain the functions of each file and relevant configuration instructions

a> pom.xml mainly adds redis jar

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
 
    <!-- redis -->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
    </dependency>
 
    <!-- Log4J -->
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
 
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

  

b> The project still adopts the default springboot configuration file - application.properties. In the configuration file, the tomcat port is mainly configured (8080 by default, which is changed to 9999 in this project. If the tomcat port is 8080 by default, there is no need to add the server.port configuration), as well as the related configuration of redis.

Note: different versions of springboot have different redis configurations. Redis's pool attribute was encapsulated in jedis after springboot version 1.4. The springboot version of this project is 2.0.4, so the configuration is as follows:

server.port=9999
#redis
spring.redis.hostName=132.232.28.164
spring.redis.port=6379    
#The springboot version is the RedisProperties configuration file class in 2.0.2 release. As can be seen from the figure, the pool property is encapsulated in the internal static classes Jedis and lettue
spring.redis.jedis.pool.max-active=8
# 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=8
# Minimum free connections in connection pool
spring.redis.jedis.pool.min-idle=0
# Connection timeout (MS)
spring.redis.timeout=0


c> jedis configuration class config -- > redisconfig.java

At the beginning of the introduction, jedis does not need to be injected and called directly. If you want to inject into spring, you need to create a jedis configuration file. The function of the configuration file is to inject jedis when the project is started, and then we can get the information of JedisPool class in other classes.

RedisConfig.java is as follows:

package com.xz.spring_redis.config;
 
import org.apache.log4j.Logger;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
 
/**
 *
 * @author vic
 * @desc redis config bean
 *
 */
@Component//For spring boot1.5 and above @ ConfigurationProperties, the alternative scheme cannot resolve method location and @ EnableConfigurationProperties are substitution relationships
//@ Component or @ configuration is not used, so this object will not be registered in the Spring container, and @ EnableConfigurationProperties are required
@PropertySource("classpath:application.properties")//Use @ PropertySource to specify a custom resource directory
@ConfigurationProperties(prefix = "spring.redis") //Read the variable value starting with "spring.redis" in the application.properties file.
public class RedisConfig {
 
    private static Logger logger = Logger.getLogger(RedisConfig.class);
 
    private String hostName;
 
    private int port;
 
    //private String password;
 
    private int timeout;
 
 
    //@Bean / / injecting JedisPoolConfig object here is meaningless and unnecessary
    public JedisPoolConfig getRedisConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        return config;
    }
 
    @Bean//@The bean annotation defines the return value of a method of a configuration class as a bean and registers it in spring
    public JedisPool getJedisPool(){
        JedisPoolConfig config = getRedisConfig();
        JedisPool pool = new JedisPool(config,hostName,port);
        logger.info("init JredisPool ...");
        return pool;
    }
 
    public String getHostName() {
        return hostName;
    }
 
    public void setHostName(String hostName) {
        this.hostName = hostName;
    }
 
    public int getPort() {
        return port;
    }
 
    public void setPort(int port) {
        this.port = port;
    }
 
    public int getTimeout() {
        return timeout;
    }
 
    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
 
}


First understand

1. The purpose of this configuration class is to register JedisPool instances in spring to facilitate Autowired JedisPool objects in other places;

2. Meanings of several annotations in the configuration class:

@ConfigurationProperties:

1. @ ConfigurationProperties(prefix = "spring.redis") / / read the variable value starting with "spring.redis" in the application.properties file.
2. Both @ ConfigurationProperties and @ value inject external properties into objects
3. @ ConfigurationProperties is easy to use. Is it better than @ value annotation? In a particular scenario, yes, it's just a matter of choice
@PropertySource:

@PropertySource("classpath:application.properties") / / use @ PropertySource to specify a custom resource directory
@Component annotation means:

Define a class as an annotation for a bean. For example, @ Component,@Service,@Controller,@Repository

@EnableConfigurationProperties:

1. If there are no @ Component,@Service,@Controller,@Repository annotations, they can be defined as bean s through @ EnableConfigurationProperties.

2. @ EnableConfigurationProperties / / enable property injection. With this annotation, you can inject through @ autowired. It is used in conjunction with @ ConfigurationProperties. If there is no @ EnableConfigurationProperties, you need to add @ Component (@ Component's wrapper annotations, such as @ Configuration and @ Service, but the essence is @ Component) to the class annotated with @ ConfigurationProperties.

3. @ EnableAutoConfiguration starts auto configuration tries to be as intelligent as possible and will back away as you define more of your own configuration.

 

The purpose of redis configuration class is to use @ ConfigurationProperties to fill Bean properties with external configuration, that is, to fill Bean properties in the configuration class by obtaining variable values in application.properties.

The specific methods are as follows:

Method 1: @ configurationproperties + @ Component annotation to bean definition class
Method 2: @ configurationproperties + @ bean annotation is on the bean definition method of the configuration class
Method 3: @ configurationproperties is annotated into a common class, and then defined as a bean through @ EnableConfigurationProperties
Source: https://blog.csdn.net/andy_zhang2007/article/details/78761651

Focus on mode 2, because this is the mode used in this project. The details are as follows:

@Component: indicates that this class is a bean

@PropertySource("classpath:application.properties"): Specifies the path to the springboot configuration file

@ConfigurationProperties(prefix = "spring.redis"): read the variable value from the springboot default configuration file (application.properties), and assign it to three variables: hostname, port and timeout (of course, more variables can be read)

//@Bean / / injecting JedisPoolConfig object here is meaningless and unnecessary
public JedisPoolConfig getRedisConfig(){
    JedisPoolConfig config = new JedisPoolConfig();
    return config;
}
 
@Bean//@The bean annotation defines the return value of a method of a configuration class as a bean and registers it in spring
public JedisPool getJedisPool(){
    JedisPoolConfig config = getRedisConfig();
    JedisPool pool = new JedisPool(config,hostName,port);
    logger.info("init JredisPool ...");
    return pool;
}


@The bean annotation placed in front of the method in the configuration class means that the object returned by this method is defined as a bean and registered in spring. The advantage of this is to avoid reloading the application.xml file. (Information: https://www.cnblogs.com/s648667069/p/6489557.html , very important!!!) for example, the getJedisPool method returns a jedispool object, which is registered as a bean, and can be directly used in the service layer later

@Autowired
private JedisPool jedisPool;
However, there is no need to add @ bean annotation to the getRedisConfig method, because this object does not need to be automatically injected later.

 

d> service layer -- > redisservice.java and RedisServiceImpl.java

RedisService.java: interface class that defines some redis methods

package com.xz.spring_redis.service;
import redis.clients.jedis.Jedis;
 
 
public interface RedisService {
 
    public Jedis getResource();
 
    public void returnResource(Jedis jedis);
 
    public void set(String key, String value);
 
    public String get(String key);
}

RedisServiceImpl.java: implementation class and some methods to implement redis

package com.xz.spring_redis.service;
 
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
 
/**
 *
 * @desc resdis service
 *
 */
@Service
public class RedisServiceImpl implements RedisService {
 
    private static Logger logger = Logger.getLogger(RedisServiceImpl.class);
 
    @Autowired
    private JedisPool jedisPool;    //jedisPool does not belong to the redis class supported by the spring boot framework, so it needs to be injected into spring by itself. Injected through the RedisConfig class
 
    @Override
    public Jedis getResource() {
        return jedisPool.getResource();
    }
 
    @SuppressWarnings("deprecation")
    @Override
    public void returnResource(Jedis jedis) {
        if(jedis != null){
            jedisPool.returnResourceObject(jedis);
        }
    }
 
    @Override
    public void set(String key, String value) {
        Jedis jedis=null;
        try{
            jedis = getResource();
            jedis.set(key, value);
            logger.info("Redis set success - " + key + ", value:" + value);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + value);
        }finally{
            returnResource(jedis);
        }
    }
 
    @Override
    public String get(String key) {
        String result = null;
        Jedis jedis=null;
        try{
            jedis = getResource();
            result = jedis.get(key);
            logger.info("Redis get success - " + key + ", value:" + result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + result);
        }finally{
            returnResource(jedis);
        }
        return result;
    }
 
}

  

 

e> controller -- "DemoController.java", the reason why Autowired RedisService can be used is that the @ service annotation is added to this class, which is expressed as a bean

package com.xz.spring_redis.controller;
 
import com.xz.spring_redis.model.ResponseModal;
import com.xz.spring_redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class DemoController {
 
    @Autowired
    private RedisService redisService;
 
 
    @RequestMapping("/redis/set")
    public ResponseModal redisSet(@RequestParam("value")String value){
        redisService.set("name", value);
        return new ResponseModal(200, true, "success", null);
    }
 
    @RequestMapping("/redis/get")
    public ResponseModal redisGet(){
        String name = redisService.get("name");
        return new ResponseModal(200, true,"success",name);
    }
 
 
}


f> Models are view related data that define the message return format

Model.java

package com.xz.spring_redis.model;
 
public class Modal {
   
 
   public Modal() {
      super();
   }
 
   public Modal(int code, boolean success, String message) {
      super();
      this.code = code;
      this.success = success;
      this.message = message;
   }
 
   private int code;
   
   private boolean success;
   
   private String message;
 
   public int getCode() {
      return code;
   }
 
   public void setCode(int code) {
      this.code = code;
   }
 
   public boolean isSuccess() {
      return success;
   }
 
   public void setSuccess(boolean success) {
      this.success = success;
   }
 
   public String getMessage() {
      return message;
   }
 
   public void setMessage(String message) {
      this.message = message;
   }
   
}


ResponseModal.java

  

package com.xz.spring_redis.model;
 
import java.io.Serializable;
 
public class ResponseModal extends Modal implements Serializable{
 
   private static final long serialVersionUID = 1L;
   
   public ResponseModal(){
      super();
   }
   
   public ResponseModal(int code,boolean success,String message){
      super(code,success,message);
   }
   
   public ResponseModal(int code,boolean success,String message,Object obj){
      super(code,success,message);
      this.response = obj;
   }
   
   private Object response;
 
   public Object getResponse() {
      return response;
   }
 
   public void setResponse(Object response) {
      this.response = response;
   }
   
}


g> The startup class has not been modified (because @ service and @ controller annotations have been added to the service layer and controller layer, it is not necessary to add @ EnableConfigurationProperties. In addition, because it does not involve the operation of dao layer or mapper layer, the @ MapperScanner annotation is not used to scan the mapper package)

  

package com.xz.spring_redis;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class SpringRedisApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringRedisApplication.class, args);
    }
}


4. So far, the key points of the project have been explained. To sum up:

1) There are two ways to configure maven for redis:

Method 1: Based on the redistemplate class, redistemplate is a redis management tool provided by springdate. springboot can be injected directly.

Method 2: Based on jedis, jedis is a Java oriented Redis client officially recommended by Redis. Jedis can be called directly without injection. If you want to inject into spring, you need to create a jedis configuration file. The function of the configuration file is to inject jedis when the project is started, and then we can get the information of JedisPool class in other classes.

(2) In the application.properties configuration, the configuration of redis is different depending on the version of springboot. Redis's pool attribute was encapsulated in jedis after springboot version 1.4.

(3) The meaning of several notes

@ConfigurationProperties:

1. @ ConfigurationProperties(prefix = "spring.redis") / / read the variable value starting with "spring.redis" in the application.properties file. 2. Both @ ConfigurationProperties and @ value inject external properties into objects

3. @ ConfigurationProperties is easy to use. Is it better than @ value annotation? In a particular scenario, yes, it's just a matter of choice

@PropertySource:

@PropertySource("classpath:application.properties") / / use @ PropertySource to specify a custom resource directory
@Component annotation means:

Define a class as an annotation for a bean. For example, @ Component,@Service,@Controller,@Repository

@EnableConfigurationProperties:

1. If there are no @ Component,@Service,@Controller,@Repository annotations, they can be defined as bean s through @ EnableConfigurationProperties.

2. @ EnableConfigurationProperties / / enable property injection. With this annotation, you can inject through @ autowired. It is used in conjunction with @ ConfigurationProperties. If there is no @ EnableConfigurationProperties, you need to add @ Component (@ Component's wrapper annotations, such as @ Configuration and @ Service, but the essence is @ Component) to the class annotated with @ ConfigurationProperties.

3. @ EnableAutoConfiguration starts auto configuration tries to be as intelligent as possible and will back away as you define more of your own configuration.

(4) The role of @ bean in the configuration class in front of the method

This means that the object returned by this method is defined as a bean and registered in spring. The advantage of this is to avoid reloading the application.xml file.

(Information: https://www.cnblogs.com/s648667069/p/6489557.html , very important!!!)

For example, the getJedisPool method returns a jedispool object registered as a bean, which can be directly used in the service layer later.

Tags: Redis

Posted on Thu, 02 Dec 2021 22:22:50 -0500 by c_coder