编程知识 cdmana.com

Integrating redis with spring boot

1. redis Introduce

Redis(Remote Dictionary Server ), Remote dictionary service , Is an open source use ANSI C Language writing 、 Support network 、 Log type that can be memory based or persistent 、Key-Value database , And provide multilingual API. from 2010 year 3 month 15 The date of ,Redis Development work by VMware host . from 2013 year 5 Month begins ,Redis The development of the Pivotal sponsorship .

2. install Redis

Its installation

3. Spring Boot Integrate Redis

3.1 Dependency import

 <!-- introduce redis rely on -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.4.0</version>
        </dependency>

<!-- Because of the use of fastJson, So we introduce dependencies -->
 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>

3.2 stay Application.yml To configure redis

spring:
  redis:
    host: 127.0.0.1  # To configure redis The host address of , It needs to be changed into your own 
    database: 5
    port: 6379
    password: # Set your own password 
    jedis:
      pool:
        max-active: 50 #  If the assignment is -1, It means no limit ; If pool Has been allocated maxActive individual jedis example , Now pool  The status of is exhausted( Run out of )
        max-idle: 20 #  The maximum free connection in the connection pool , The default value is also 8.
        min-idle: 5  #  The smallest free connection in the connection pool , The default value is also 0.
       # max-wait: 5 #  The maximum time to wait for an available connection , Unit millisecond , The default value is -1, Means never time out . If the wait time is exceeded , directly   Throw out JedisConnectionException

3.3 redis Commonly used APi Introduce

redis Provides RedisTemplate and StringRedisTemplate Templates . What I use below is StringRedisTemplate demonstrate :

@Component
public class RedisService {
   
   
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //string  type 
    /*

	 Create a new one  RedisService, Inject  StringRedisTemplate, Use  		stringRedisTemplate.opsForValue()
 Can get  ValueOperations<String, String>  object , You can read and write through this object  redis  Database .
*/
    public void setRediskv(String key,String value){
   
   
        ValueOperations<String, String> forValue = stringRedisTemplate.opsForValue();
        forValue.set(key,value);


    }
    public String getRediskv(String key){
   
   
        String s = stringRedisTemplate.opsForValue().get(key);
        return s;
    }


    //String Types store objects , Convert the object to json data type 
    public void setRedisObj(User user){
   
   

        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        stringStringValueOperations.set("user", JSON.toJSONString(user));

    }
    public User getRedisObj(){
   
   
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        String user = stringStringValueOperations.get("user");
        User user1 = JSONObject.parseObject(user, User.class);
        return user1;
    }

    //list type 
/*

 Use  stringRedisTemplate.opsForList()  Can get  ListOperations<String, String> listOperations redis  List objects , This list is a simple list of strings , It can support adding from the left side , Can also support 
 Add... From the right , A list can contain at most  2 ^ 32 -1  Elements .

*/
    public void setRedisList(){
   
   

        ListOperations<String, String> stringStringListOperations = stringRedisTemplate.opsForList();
       stringStringListOperations.leftPush("list","ljz1");
       stringStringListOperations.leftPush("list","ljz2");
       stringStringListOperations.leftPush("list","ljz3");
       stringStringListOperations.leftPush("list","ljz4");
    }
    public String getRedisList(){
   
   
        ListOperations<String, String> stringStringListOperations = stringRedisTemplate.opsForList();
        String list = stringStringListOperations.leftPop("list");
        return list;
    }


    //hash type 
    /*
hash  The principle of type and  string  Same , But there are two  key, Use  stringRedisTemplate.opsForHash()
 Can get  HashOperations<String, Object, Object>  object . For example, we need to store order information , All orders 
 The information is put in  order  Next , Order entities for different users , You can use the user's  id  To distinguish between , This is equivalent to two  key
 了 .


*/
    public void setRedisHash(){
   
   
        HashOperations<String, Object, Object> stringObjectObjectHashOperations = stringRedisTemplate.opsForHash();
        stringObjectObjectHashOperations.put("hash0","name0","ljz0");
        stringObjectObjectHashOperations.put("hash1","name1","ljz1");
        stringObjectObjectHashOperations.put("hash2","name2","ljz2");


    }
    public Object getRedisHash(){
   
   
        HashOperations<String, Object, Object> stringObjectObjectHashOperations = stringRedisTemplate.opsForHash();
        Object o = stringObjectObjectHashOperations.get("hash0", "name0");
        return o;
    }
}

The test case :

package liz.com.springtest.controller;

import liz.com.springtest.entity.User;
import liz.com.springtest.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author linjiazeng
 * @version 1.0
 * @date 2020/12/23 10:52
 **/
@RestController
@RequestMapping("redis")
public class RedisController {
   
   

    @Autowired
    private RedisService redisService;

    // test String type 
    @GetMapping("setRedis/{key}/{name}")
    public String setReids(@PathVariable String key,@PathVariable String name ){
   
   
        redisService.setRediskv(key,name);
        return "success";
    }

    @GetMapping("getRedis/{key}")
    public String getReids(@PathVariable String key){
   
   
        String redis = redisService.getRediskv(key);
        return redis;
    }

    // Test object type 
    @GetMapping("setRedisObj")
    public String setRedisObj(){
   
   
        User user = new User();
        user.setName("ljz");
        user.setAge("18");
        user.setSex(" male ");
        redisService.setRedisObj(user);
        return "success";
    }

    @GetMapping("getRedisObj")
    public User getRedisObj(){
   
   
        return redisService.getRedisObj();
    }

    // test list type 
    @GetMapping("setRedisList")
    public String setRedisList(){
   
   
        redisService.setRedisList();
        return "success";
    }

    @GetMapping("getRedisList")
    public String getRedisList(){
   
   
        return redisService.getRedisList();
    }

    // test hash
    @GetMapping("getRedisHash")
    public Object getRedisHash(){
   
   
        return redisService.getRedisHash();
    }

    @GetMapping("setRedisHash")
    public String setRedisHash(){
   
   
        redisService.setRedisHash();
        return  "success";
    }
}

Some of the test results are as follows :
Use now when testing http://localhost:8080/redis/setRedisObj Cache data to reids, And then visit again http://localhost:8080/redis/getRedisObj
 Insert picture description here

版权声明
本文为[osc_ eijjkem1]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225102952088Q.html

Scroll to Top