Redis Learning Notes: Java uses Jedis to connect Redis instances (the difference between using String and hash types to store objects)

Posted by boonika on Thu, 11 Jun 2020 18:11:27 +0200

Foreword: When we need to operate on redis, we need to start the redis-server service first, then start the redis-cli client to connect to the redis server to operate on it, or we can connect redis directly with the visual operation tool to operate on it.But what should we do if we need java programs to manipulate redis?
At this point, we can use jedis to operate redis, which is a tool for connecting redis for java programs.

Article Directory

One.Example description

This example simulates a common use scenario for redis, using redis as a cache.When querying data, we first look for the data we need from redis. If redis exists, we read the data directly from redis, return it to the interface, and do not query the database. If redis does not exist, we query the database, read the data from the database, return it to the interface, and put the data into redis.The next time you query the same data, you can query directly in redis instead of the database.
This has the advantage of effectively reducing the pressure on the database and improving the performance of the system when the data is large and concurrent, because redis is a memory-based, non-relational database and can be read very quickly.

Two.Operational steps (using String to store objects)

1. Step 1, inPom.xmlAdd Jedis dependencies to the file:

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

2. Step 2, Create a new oneRedis.propertiesConfiguration file, configure redis properties in the configuration file:

#redis startup port
redis.host=127.0.0.1
#redis connection ip
redis.port=6379
#redis password
redis.password=123456
#Maximum number of redis connections
redis.maxTotal=30
#redis controls how many jedis instances a pool can allocate (maximum number of idle connections)
redis.maxIdle=10

3. Step 3, create a new JedisUtils tool class to readRedis.propertiesConfiguration file, returns a jedis connection object based on the configuration file:

package cn.com.do1.common.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ResourceBundle;

public class JedisUtils {
    //Read external redis profile
    private static ResourceBundle rb = ResourceBundle.getBundle("redis");
    //Read to redis startup port
    private static int port = Integer.parseInt(rb.getString("redis.port"));
    //Read to redis connection ip
    private static String host = rb.getString("redis.host");
    //Read redis password
    private static String password = rb.getString("redis.password");
    //Maximum number of connections read to redis
    private static int maxTotal = Integer.parseInt(rb.getString("redis.maxTotal"));
    //Read to redis controls how many jedis instances a pool can allocate (maximum number of idle connections)
    private static int maxIdle = Integer.parseInt(rb.getString("redis.maxIdle"));

    private static JedisPoolConfig jpc = new JedisPoolConfig();
    //Configure redis according to configuration
    private static JedisPool jp = new JedisPool(jpc,host,port);

    //Returns a jedis connection object
    public static Jedis getJedis(){
        //Provides a jedis connection object, the connection is obtained from the connection pool
        Jedis jedis = jp.getResource();
        //Set connection password
        jedis.auth(password);
        return  jedis;
    }
}

4. The memberVo entity class is as follows:

package cn.com.do1.user.model;

import java.util.Date;

/**
 * User vo
 * @author : zhongkaisheng
 */
public class MemberVO {
    private Integer id;

    /*
    User name
    */
    private String username;

    /*
    Password
   */
    private String password;

    /*
    Phone number
   */
    private String phone;

    /*
    Mail box
   */
    private String email;

    /*
    Account Creation Time
   */
    private Date createTime;

    /*
    Account Modification Time
    */
    private Date updateTime;

    /*
   integral
   */
    private Double integral;

    /*
    Last logon time
    */
    private Date lastTime;

    /*
    Amount of money
    */
    private String money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Double getIntegral() {
        return integral;
    }

    public void setIntegral(Double integral) {
        this.integral = integral;
    }

    public Date getLastTime() {
        return lastTime;
    }

    public void setLastTime(Date lastTime) {
        this.lastTime = lastTime;
    }

    public String getMoney() {
        return money;
    }

    public void setMoney(String money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "MemberVO{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", phone='" + phone + '\'' +
                ", email='" + email + '\'' +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                ", integral=" + integral +
                ", lastTime=" + lastTime +
                ", money='" + money + '\'' +
                '}';
    }
}

5. Step 4. Simulate the relevant business logic in the controller, where we convert the object into a json string and store it with the String type in redis:

/**
     * redis Testing (using String to store objects)
     * @param id
     * @return
     * @throws IOException
     */
    @RequestMapping("redisTest")
    @ResponseBody
    public Object redisTest(@RequestParam(required = false) Integer id) throws IOException {
        //Initialize json object
        JSONObject jsonData=new JSONObject();
        String s="";
        //value stored in redis
        String object="";
        //key stored in redis
        String key = "tb_member:id:"+id;
        MemberVO memberVO=new MemberVO();
        ObjectMapper objectMapper=new ObjectMapper();
        //Get the jedis object
        Jedis jedis=JedisUtils.getJedis();
        //If redis contains the key value
        if(jedis.get(key)!=null){
            s="Query is for cache";
            //Get the value of the key in redis
            object=jedis.get(key);
            //Converts the json string holding the object in value to an object
            memberVO=objectMapper.readValue(object,MemberVO.class);
        }
        //If the key value is not included in redis
        else{
            //Find the object by id
            memberVO=memberService.getMbmberById(id);
            //Converting Objects to json Strings
            object= JSONObject.toJSONString(memberVO);
            s="The query is for a database";
            //Insert in redis
            jedis.set(key,object);

        }
        //Save in a json object
        jsonData.put("s",s);
        jsonData.put("object",object);
        jsonData.put("memberVO",memberVO);
        //Return to json
        return jsonData;
    }

6. Step 5, use Postman to invoke the interface:

7. Step 6, open the redis visualizer to see that the josn object has been saved in redis of type string:

8. When calling the interface again, take the data directly from redis without accessing the database:

Three.Storing objects using hash types in redis

1. The corresponding interface code in the controller is as follows:

 /**
     * redis Testing (using hash to store objects)
     * @param id
     * @return
     */
    @RequestMapping("redisTest1")
    @ResponseBody
    public Object redisTest1(@RequestParam(required = false) Integer id) {
        //Initialize json object
        JSONObject jsonData=new JSONObject();
        String s="";
        //value stored in redis
        List<String> object=new ArrayList<>();
        //key stored in redis
        String key = "memberVO";
        MemberVO memberVO=new MemberVO();
        ObjectMapper objectMapper=new ObjectMapper();
        //Get the jedis object
        Jedis jedis=JedisUtils.getJedis();
        //If the value corresponding to the file id in redis is not empty, the data exists in redis
        if(jedis.hget(key,"id")!=null){
            s="Query is for cache";
            //Assign values to objects based on values stored in redis
            memberVO.setId(Integer.parseInt(jedis.hget(key,"id")));
            memberVO.setUsername(jedis.hget(key,"username"));
            memberVO.setPassword(jedis.hget(key,"password"));
            memberVO.setPhone(jedis.hget(key,"phone"));
            memberVO.setMoney(jedis.hget(key,"money"));
            memberVO.setEmail(jedis.hget(key,"email"));
        }
        //If the key value is not included in redis
        else{
            //Find the object by id
            memberVO=memberService.getMbmberById(id);
            s="The query is for a database";
            //Insert in redis
            jedis.hset(key,"id",String.valueOf(memberVO.getId()));
            jedis.hset(key,"username",memberVO.getUsername());
            jedis.hset(key,"password",memberVO.getPassword());
            jedis.hset(key,"phone",memberVO.getPhone());
            jedis.hset(key,"email",memberVO.getEmail());

        }
        //Save in a json object
        jsonData.put("s",s);
        jsonData.put("memberVO",memberVO);
        //Return to json
        return jsonData;
    }

2. Call the interface for the first time:

3. Open the redis visualizer to see that the object has been saved in redis of type hash:

4. When calling the interface again, take the data directly from redis without accessing the database:

summary

The common data types used by redis to store objects are String and Hash.
String is similar to String in java. String stores json string converted from object, which is suitable for reading. You can find the corresponding json string according to the corresponding key and get all the attributes of the object, but it is particularly troublesome to modify. If the object has 30 attributes, I only need to modify one of them, I also need to reassign the other attributes, and then set into redis, change everything, many more unnecessary operations, reduced performance.
Hash stores objects to solve this problem perfectly. Hash is similar to Map in java. You only need to know that you need to modify the key and filed values of the object's properties. Then you can modify them by removing a new value from hset based on the key and filed. You don't need to modify all the properties, but hash can be more cumbersome to read and needs one to read.Both have obvious advantages and disadvantages, and can be selected according to the actual application scenario.

Topics: Redis Jedis JSON Database