Redis practice Spring Boot2.0 integrate redis custom injection template operation Bean component

Overview: the related content of this series of blog articles comes from the actual combat course recorded by debug in person: Introduction to Redis technology and application scenario practice (SpringBoot2.x + red packet system design and practice) , interested partners can click to learn by themselves (after all, mastering technology in the form of video will be faster!) , column: Introduction and practice of Redis Technology

Absrtact: for Redis, I believe that many small partners have heard about it. What's more, they have applied it to many projects! Yes, it is one of the cache middleware widely used in the industry at present, and it can also be regarded as the leader. Starting from this article, we will lay the foundation for the microservice project based on spring boot 2.0 integration, and start the real battle road of Redis middleware!

Content: in this article, we will first build Redis, a project integrated caching middleware based on SpringBoot2.0, add common configuration information related to Redis in the project, and customize the template operation components StringRedisTemplate and RedisTemplate injected into Redis, and finally give you a simple Demo and start Redis's practical journey!

(1) The first step is to add the dependency Jar of Redis, as shown below:

        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.3.3.RELEASE</version>
        </dependency>

Then add the common configuration information of Redis in the configuration file application.properties, including the basic information such as host and port. Here we provide two configuration modes, namely "stand-alone mode" and "cluster mode", as follows:

#redis stand-alone configuration
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=

spring.redis.jedis.pool.min-idle=100
spring.redis.jedis.pool.max-idle=300
spring.redis.jedis.pool.max-active=500

#Cluster configuration
#spring.redis.cluster.nodes=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382

In this configuration file, we also add the concept of "link pool", in which the minimum number of links available in the link pool is 100, and the maximum number of connections available is 300. If it is not enough and needs dynamic amplification, we will eventually increase the number of active links to 500! (if 500 is not enough, you have to wait. During the waiting period, if the time exceeds the default timeout, an error similar to connection reset or connection error will be reported.)


(2) Next, we will inject Redis's operation template components based on the built project customization, which are mainly StringRedisTemplate and RedisTemplate. It is worth mentioning that in traditional Java Web projects, such as spring + spring MVC + mybatis integrated projects, a JedisUtil tool class is directly encapsulated based on Jedis, which is similar to the previous way of using JDBC util to operate DB database, and its defects are more obvious (such as the need to manually create links, close link resources and other operations)


However, the advent of Spring Boot has brought the advantages of "Convention takes precedence over configuration" and "start dependence", which saves many operations that may consume resources in the past, such as manually creating and closing links. That is, it is directly built into the start dependence of Spring Boot Redis. For how to operate Redis more conveniently, Spring Boot directly encapsulates and provides two templates Operation components StringRedisTemplate and RedisTemplate. As shown below, we inject these two template operation components by customization, that is, we mainly specify the serialization related policies:

/**
 * @EnableCaching: Enable cache (annotation effective)
 * redis Operation component custom injection configuration of
 * @Author:debug (SteadyJack)
 * @Link: wx-> debug0868  qq-> 1948831260
 * @Date: 2019/10/29 16:59
 **/
@Configuration
@EnableCaching
public class RedisConfig {
 
    @Autowired
    private RedisConnectionFactory connectionFactory;
 
    @Bean
    public RedisTemplate redisTemplate(){
        RedisTemplate<String,Object> redisTemplate=new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        //Set serialization policy
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
 
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
 
    @Bean
    public StringRedisTemplate stringRedisTemplate(){
        StringRedisTemplate stringRedisTemplate=new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(connectionFactory);
        return stringRedisTemplate;
    }
}


(3) So far, we have made the relevant Prelude preparations. Next, we will write a simple Demo, which means "open the real battle road of Redis":

/**
 * @Author:debug (SteadyJack)
 * @Link: weixin-> debug0868 qq-> 1948831260
 * @Date: 2019/10/29 15:47
 **/
@RestController
@RequestMapping("base")
public class BaseController {
 
    private static final Logger log= LoggerFactory.getLogger(BaseController.class);
 
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
 
    private static final String RedisHelloWorldKey="SpringBootRedis:HelloWorld";
 
    @RequestMapping(value = "/hello/world/put",method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse helloWorldPut(@RequestParam String helloName){
        BaseResponse response=new BaseResponse(StatusCode.Success);
        try {
            stringRedisTemplate.opsForValue().set(RedisHelloWorldKey,helloName);
            response.setData("hello world!");
        }catch (Exception e){
            log.info("--hello world get Exception information: ",e.fillInStackTrace());
            response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }
 
    @RequestMapping(value = "/hello/world/get",method = RequestMethod.GET)
    @ResponseBody
    public BaseResponse helloWorldGet(){
        BaseResponse response=new BaseResponse(StatusCode.Success);
        try {
            String result=stringRedisTemplate.opsForValue().get(RedisHelloWorldKey);
            response.setData(result);
        }catch (Exception e){
            log.info("--hello world get Exception information: ",e.fillInStackTrace());
            response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }
}


The above code is a simple String data type based on Redis to store a specific String of information (in this case, a String constant value is passed from the front end!)


(4) Finally, we conduct self-test based on Postman (learning self-test is a necessary skill and good habit for a Java siege lion). Two figures can be summarized:




Well, we've introduced this article here. I suggest that you should follow the sample code provided in this article, and only after it can you know how to use it, otherwise you will become a "talker"! Those who are interested in Redis related technology stack and practical application scenario can learn from the course recorded by 51cto college debug in person: Introduction to Redis technology and application scenario practice (SpringBoot2.x + red packet system design and practice)

Supplement:

1. The relevant source code involved in this article can be check ed at this address for viewing and learning: https://gitee.com/steadyjack/SpringBootRedis

2. At present, debug has organized and recorded the content involved in this article into a video tutorial. Interested partners can go to watch and learn: https://edu.51cto.com/course/20384.html


Tags: Java Redis Spring Jedis

Posted on Thu, 06 Feb 2020 04:28:54 -0500 by sara_kovai