编程知识 cdmana.com

The latest redis picture and text course (Part 2)

Java operation Redis

Create project

Create project

image38

 Insert picture description here

Add dependency

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.xxxx</groupId>
    <artifactId>redisdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>redisdemo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- spring data redis  Components  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <!--
                1.x  The default connection pooling technology adopted by the version of is  Jedis,
                2.0  The default connection pool of the above version is  Lettuce,
                 If the  Jedis, Need to be excluded  Lettuce  Dependence .
             -->
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- jedis  rely on  -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <!-- web  Components  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- test  Components  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

The configuration file

spring:
  redis:
    # Redis Server address 
    host: 192.168.10.100
    # Redis Server port 
    port: 6379
    # Redis Server password 
    password: root
    #  Which library to choose , Default 0 library 
    database: 0
    #  Connection timeout 
    timeout: 10000ms
    jedis:
      pool:
        #  maximum connection , Default 8
        max-active: 1024
        #  Maximum connection blocking wait time , Unit millisecond , Default -1ms
        max-wait: 10000ms
        #  Maximum free connection , Default 8
        max-idle: 200
        #  Minimum free connection , Default 0
        min-idle: 5

Java How to connect Redis?

/**
 *  Connect Redis
 */
@Test
public void initConn01() {
    //  establish jedis object , Connect redis service 
    Jedis jedis = new Jedis("192.168.10.100", 6379);

    //  Set authentication password 
    jedis.auth("root");

    //  Specify database   The default is 0
    jedis.select(1);

    //  Use ping command , Test connection success 
    String result = jedis.ping();
    System.out.println(result);//  return PONG

    //  Add a piece of data 
    jedis.set("username", "zhangsan");

    //  Get a piece of data 
    String username = jedis.get("username");
    System.out.println(username);

    //  Release resources 
    if (jedis != null)
        jedis.close();
}

adopt Redis The connection pool gets the connection object and operates the server

/**
 *  adopt Redis Connection pool get connection object 
 */
@Test
public void initConn02() {
    //  initialization redis Client connection pool 
    JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), "192.168.10.100", 6379, 10000, "root");

    //  Get connection from connection pool 
    Jedis jedis = jedisPool.getResource();

    //  Specify database   The default is 0
    jedis.select(2);

    //  Use ping command , Test connection success 
    String result = jedis.ping();
    System.out.println(result);//  return PONG

    //  Add a piece of data 
    jedis.set("username", "zhangsan");

    //  Get a piece of data 
    String username = jedis.get("username");
    System.out.println(username);

    //  Release resources 
    if (jedis != null)
        jedis.close();
}

encapsulation JedisUtil Provide connection object acquisition method

@Configuration
public class RedisConfig {
    // Server address 
    @Value("${spring.redis.host}")
    private String host;
    // port 
    @Value("${spring.redis.port}")
    private int port;
    // password 
    @Value("${spring.redis.password}")
    private String password;
    // Timeout time 
    @Value("${spring.redis.timeout}")
    private String timeout;
    // maximum connection 
    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxTotal;
    // Maximum connection blocking wait time 
    @Value("${spring.redis.jedis.pool.max-wait}")
    private String maxWaitMillis;
    // Maximum free connection 
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;
    // Minimum free connection 
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;


    @Bean
    public JedisPool redisPoolFactory(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // Pay attention to the shift of values 
  jedisPoolConfig.setMaxWaitMillis(Long.parseLong(maxWaitMillis.substring(0,maxWaitMillis.length()-2)));
        // Note the property name 
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, Integer.parseInt(timeout.substring(0,
                timeout.length() - 2)), password);
        return jedisPool;
    }
}

Java operation Redis Five types of data

Connect and release

@Autowired
private JedisPool jedisPool;

private Jedis jedis = null;

// initialization jedis Object instances 
@Before
public void initConn(){
    jedis = jedisPool.getResource();
}

// Release resources 
@After
public void closeConn(){
    if (jedis!=null){
        jedis.close();
    }
}

operation String

// 1. operation String
@Test
public void testString() {
   //  Add a piece of data 
   jedis.set("username", "zhangsan");
   jedis.set("age", "18");
   
   //  Add multiple pieces of data   The odd number of parameters is key  The even number of parameters is value
   jedis.mset("address", "bj", "sex", "1");
   
   //  Get a piece of data 
   String username = jedis.get("username");
   System.out.println(username);
   
   //  Get multiple pieces of data 
   List<String> list = jedis.mget("username", "age", "address", "sex");
   for (String str : list) {
      System.out.println(str);
   }
   
   //  Delete 
   //jedis.del("username");
}

operation hash

// 2. operation Hash
@Test
public void testHash() {
   /*
    *  Add a piece of data 
    *      Parameter one :redis Of key
    *      Parameter two :hash Of key
    *      Parameter 3 :hash Of value
    */
   jedis.hset("userInfo", "name", "lisi");
   
   //  Add multiple pieces of data 
   Map<String, String> map = new HashMap<>();
   map.put("age", "20");
   map.put("sex", "1");
   jedis.hmset("userInfo", map);
   
   //  Get a piece of data 
   String name = jedis.hget("userInfo", "name");
   System.out.println(name);
   
   //  Get multiple pieces of data 
   List<String> list = jedis.hmget("userInfo", "age", "sex");
   for (String str : list) {
      System.out.println(str);
   }
   
   //  obtain Hash Type all the data 
   Map<String, String> userMap = jedis.hgetAll("userInfo");
   for (Entry<String, String> userInfo : userMap.entrySet()) {
      System.out.println(userInfo.getKey() + "--" + userInfo.getValue());
   }
   
   //  Delete   Used to delete hash Type data 
   //jedis.hdel("userInfo", "name");
}

operation list

    // 3. operation list
   @Test
   public void testList() {
      //  Add left ( On )
//    jedis.lpush("students", "Wang Wu", "Li Si");
      
      //  Right add ( Next )
//    jedis.rpush("students", "Zhao Liu");
      
      //  obtain  start Start subscript  end End subscript   Inclusion relation 
      List<String> students = jedis.lrange("students", 0, 2);
      for (String stu : students) {
         System.out.println(stu);
      }
      
      //  Get the total number 
      Long total = jedis.llen("students");
      System.out.println(" Total number of articles :" + total);
      
      //  To delete a single   Delete the first time that appears in the list Li Si
//    jedis.lrem("students", 1, "Li Si");
      
      //  Delete multiple 
//    jedis.del("students");
   }

operation set

// 4. operation set- disorder 
@Test
public void testSet() {
   //  Add data 
   jedis.sadd("letters", "aaa", "bbb", "ccc", "ddd", "eee");
   
   //  get data 
   Set<String> letters = jedis.smembers("letters");
   for (String letter: letters) {
      System.out.println(letter);
   }
    
    // Get the total number 
    Long total = jedis.scard("letters");
    System.out.println(total);
   
   //  Delete 
   //jedis.srem("letters", "aaa", "bbb");
}

operation sorted set

// 5. operation sorted set- Orderly 
@Test
public void testSortedSet() {
   Map<String, Double> scoreMembers = new HashMap<>();
   scoreMembers.put("zhangsan", 7D);
   scoreMembers.put("lisi", 3D);
   scoreMembers.put("wangwu", 5D);
   scoreMembers.put("zhaoliu", 6D);
   scoreMembers.put("tianqi", 2D);
   
   //  Add data 
   jedis.zadd("score", scoreMembers);
   
   //  get data 
   Set<String> scores = jedis.zrange("score", 0, 4);
   for (String score: scores) {
      System.out.println(score);
   }
   
   //  Get the total number 
   Long total = jedis.zcard("score");
   System.out.println(" Total number of articles :" + total);
   
   //  Delete 
   //jedis.zrem("score", "zhangsan", "lisi");
}

Redis There is a hierarchical relationship between China and Israel 、 Data is stored in the form of a directory

// Redis There is a hierarchical relationship between China and Israel 、 Data is stored in the form of a directory 
@Test
public void testdir(){
    jedis.set("user:01", "user_zhangsan");
    System.out.println(jedis.get("user:01"));
}

Set up key The expiration time of

Redis There are four different commands that can be used to set the lifetime of the key ( How long can the key last ) Or expiration time ( When will the key be deleted ) :

EXPlRE <key> <ttl> : Used to put the key key The lifetime of is set to ttl second .

PEXPIRE <key> <ttl>: Used to put the key key The lifetime of is set to ttl millisecond .

EXPIREAT <key> < timestamp>: Used to put the key key The expiration time for is set to timestamp The time stamp of the specified number of seconds .

PEXPIREAT <key> < timestamp > : Used to put the key key The expiration time for is set to timestamp The specified number of milliseconds timestamp .

TTL: The value obtained is -1 Illustrate this key No expiration date set , The duty of -2 It is proved that the period of validity has expired .

@Test
public void testExpire() {
    //  Method 1 :
    jedis.set("code", "test");
    jedis.expire("code", 180);// 180 second 
    jedis.pexpire("code", 180000L);// 180000 millisecond 
    jedis.ttl("code");//  Get seconds 

    //  Method 2 :
    jedis.setex("code", 180, "test");// 180 second 
    jedis.psetex("code", 180000L, "test");// 180000 millisecond 
    jedis.pttl("code");//  Get milliseconds 

    //  Method 3 :
    SetParams setParams = new SetParams();
    // Only when it doesn't exist can it be set successfully 
    // setParams.nx();
    //  It can be set successfully only when it exists 
    setParams.xx();
    // Set the expiration time , Unit second 
    // setParams.ex(30);
    // Check the expiration time , Unit millisecond 
    setParams.px(30000);
    jedis.set("code","test",setParams);
}

Get all key& Business & Delete

   //  Get all key
   @Test
   public void testAllKeys() {
      //  Current library key The number of 
      System.out.println(jedis.dbSize());
      //  Current library key The name of 
      Set<String> keys = jedis.keys("*");
      for (String key: keys) {
         System.out.println(key);
      }
   }

    //  Operational transaction 
   @Test
   public void testMulti() {
      Transaction tx = jedis.multi();
      //  Open transaction 
      tx.set("tel", "10010");
      
      //  Commit transaction 
//    tx.exec();
      
      //  Roll back the transaction 
      tx.discard();
   }
   
   //  Delete 
   @Test
   public void testDelete() {
      //  Delete   Universal   For all data types 
      jedis.del("score");
   }

operation byte

SerializeUtil.java

package com.xxxx.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 *  Serialization tool class 
 */
public class SerializeUtil {
   
   /**
    *  take java Object to byte Array   Serialization process 
    */
   public static byte[] serialize(Object object) {
      ObjectOutputStream oos = null;
      ByteArrayOutputStream baos = null;
      try {
         //  serialize 
         baos = new ByteArrayOutputStream();
         oos = new ObjectOutputStream(baos);
         oos.writeObject(object);
         byte[] bytes = baos.toByteArray();
         return bytes;
      } catch (Exception e) {
         e.printStackTrace();
      }
      return null;
   }

   /**
    *  take byte Array to java object    Deserialization 
    */
   public static Object unserialize(byte[] bytes) {
      if(bytes == null)return null;
      ByteArrayInputStream bais = null;
      try {
         //  Deserialization 
         bais = new ByteArrayInputStream(bytes);
         ObjectInputStream ois = new ObjectInputStream(bais);
         return ois.readObject();
      } catch (Exception e) {
         e.printStackTrace();
      }
      return null;
   }
}

User.java

package com.xxxx.entity;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = 9148937431079191022L;
    private Integer id;
    private String username;
    private String password;

    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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

JedisTest.java

//  operation byte
@Test
public void testByte() {
    User user = new User();
    user.setId(2);
    user.setUsername("zhangsan");
    user.setPassword("123");

    //  serialize 
    byte[] userKey = SerializeUtil.serialize("user:" + user.getId());
    byte[] userValue = SerializeUtil.serialize(user);
    jedis.set(userKey, userValue);

    //  get data 
    byte[] userResult = jedis.get(userKey);

    //  Deserialization 
    User u = (User) SerializeUtil.unserialize(userResult);
    System.out.println(u);
}

Redis Build master-slave reuse

 Redis Support master-slave reuse . Data can be synchronized from the master server to any number of slaves , Synchronization uses Publishing / Subscribe mechanism .Mater Slave The pattern of , from Slave towards Master launch SYNC command .

  It can be 1 Master many Slave, It can be layered ,Slave You can connect to Slave, It can be expanded into a tree structure .

  Because there are no two computers , So you can only build two on one machine Redis Server side .

  Here we use a single machine to simulate redis Master slave server , Realize read-write separation configuration .

Read / write separation

Create three directories ( Data files 、 Log files 、 The configuration file )

Copy redis.conf to /opt/redis/conf Under the table of contents

modify redis-common.conf Public profile

Comment out bind 127.0.0.1

Turn off protection mode , It is amended as follows no

 Insert picture description here

Comment public configuration port

Change to background start

Note process number record file

Comment public configuration log file

Comment on the public configuration data file 、 Modify data file path

  By default ,Redis Save the database snapshot in a file named dump.rdb In the binary file of . Of course , This can be modified redis.conf Configuration file to define data storage conditions , It is stipulated in “ N At least... In seconds M A change ” When this condition is met , Save the data set automatically once . You can also call save or bgsave , Let go by hand Redis Save the dataset

dbfilename and dir Use a combination of ,dbfilename look for dir Path generation data file

Add authentication from server to master server

Add access authentication

Comment public configuration append file

  Configure whether to turn on the append file option according to the requirements

 appendonly yes -> whenever Redis When executing a command to change a dataset ( such as SET), This order will be appended to AOF End of file . In this case , When Redis When you restart , The program can be re executed by AOF The command in the file to rebuild the dataset

 

 appendfilename and dir Use a combination of , look for dir(/opt/redis/data) Path generation data file

By default, the slave server is read-only and no write operations are allowed ( No need to modify )

add to 3 A private profile of a service

 touch perhaps vi Can create a blank file

 touch Create a blank file directly ,vi Create and enter edit mode ,:wq Create success , Otherwise, do not create

redis-6379.conf

# Reference public configuration 
include /opt/redis/conf/redis-common.conf
# Process number record file 
pidfile /var/run/redis-6379.pid
# Process port number 
port 6379
# Log files 
logfile "/opt/redis/log/redis-6379.log"
# Data record file 
dbfilename dump-6379.rdb
# Add file name 
appendfilename "appendonly-6379.aof"
# The following configuration does not need to be in 6379 Internal configuration 
# The backup server is subordinate to 6379 Recommended configuration with lan IP
slaveof 192.168.10.100 6379

  Copy redis-6379.conf From the content of redis-6380.conf,redis-6381.conf And modify its content , take 6379 Replace it .

function 3 individual redis process

see redis Server master-slave status

redis-6379

redis-6380

redis-6381

Add data under the master server And test whether the data from the server is displayed normally

Read only from server , Write not allowed

Active standby switching

Master slave node redis.conf To configure

reference Read / write separation The corresponding configuration of

modify sentinel-common.conf Sentinel public profile

from redis Unzip the directory to copy sentinel.conf to /opt/redis/conf/

cp sentinel.conf /opt/redis/conf/sentinel-common.conf

Note sentinel listening process port number

  instructions Sentinel To watch a man named master The primary server of , This master server's IP The address is 127.0.0.1, The port number is 6379, It is necessary to judge the primary server as invalid 1 individual ( Generally set as 2 individual ).Sentinel agree! ( Just agree to Sentinel The quantity is not up to standard , Automatic failover will not be performed ).

  This one should be equipped with LAN IP, Otherwise, remote connection will not be possible .

Set up master and slaves Password

Sentinel The number of milliseconds it takes to think the server has been disconnected

  if sentinel Failed to complete within the configuration value failover operation ( In case of failure master/slave Automatic switch ), This time failover Failure .

Turn off protection mode , It is amended as follows no

Change to background start

add to 3 A private configuration file for sentinels

touch perhaps vi Can create a blank file

touch Create a blank file directly ,vi Create and enter edit mode ,:wq Create success , Otherwise, do not create

sentinel-26379.conf

# Reference public configuration 
include /opt/redis/conf/sentinel-common.conf
# Process port number 
port 26379
# Process number record file 
pidfile /var/run/sentinel-26379.pid
# Log files ( For the convenience of viewing the log , Comment out first , After setting up the environment, open it again )
logfile "/opt/redis/log/sentinel-26379.log"

  Copy sentinel-26379.conf From the content of sentinel-26380.conf ,sentinel-26381.conf And modify its content , take 26379 Replace it .

Start the test

start-up 3 individual redis service

/usr/local/redis/bin/redis-server /opt/redis/conf/redis-6379.conf
/usr/local/redis/bin/redis-server /opt/redis/conf/redis-6380.conf
/usr/local/redis/bin/redis-server /opt/redis/conf/redis-6381.conf

start-up 3 A sentinel service

/usr/local/redis/bin/redis-sentinel /opt/redis/conf/sentinel-26379.conf
/usr/local/redis/bin/redis-sentinel /opt/redis/conf/sentinel-26380.conf
/usr/local/redis/bin/redis-sentinel /opt/redis/conf/sentinel-26381.conf

Check the master-slave status

redis-6379

redis-6380

redis-6381

Check whether the sentinel function is configured successfully

kill -9 End redis-6379, Check if the sentry has elected a new master node

Elected 6380 Master node , From the node, only 6381

Restart 6379 node , Check the master-slave status again

Find out 6379 Has been discovered and becomes a slave node

6380 You can't write before , Now you can write operations , Because it has become the master node .

Last , The public configuration file is changed to background startup , Private configuration file open log file , The environment was built successfully .## Java operation Redis

jedis.set("code","test",setParams);

}


####  Get all key& Business & Delete 

// Get all key
@Test
public void testAllKeys() {

  //  Current library key The number of 
  System.out.println(jedis.dbSize());
  //  Current library key The name of 
  Set<String> keys = jedis.keys("*");
  for (String key: keys) {
     System.out.println(key);
  }

}

//  Operational transaction 

@Test
public void testMulti() {

  Transaction tx = jedis.multi();
  //  Open transaction 
  tx.set("tel", "10010");
  
  //  Commit transaction 

// tx.exec();

  
  //  Roll back the transaction 
  tx.discard();

}

// Delete
@Test
public void testDelete() {

  //  Delete   Universal   For all data types 
  jedis.del("score");

}







** Add access authentication **



![](https://img-blog.csdnimg.cn/20201224111709664.png#pic_center)




** Comment public configuration append file **

  Configure whether to turn on the append file option according to the requirements 

 `appendonly yes` ->  whenever Redis When executing a command to change a dataset ( such as  SET), This order will be appended to  AOF  End of file . In this case , When Redis When you restart , The program can be re executed by  AOF The command in the file to rebuild the dataset 



![](https://img-blog.csdnimg.cn/20201224111721525.png#pic_center)


 

 appendfilename and dir Use a combination of , look for dir(/opt/redis/data) Path generation data file 



![](https://img-blog.csdnimg.cn/202012241117342.png#pic_center)




** By default, the slave server is read-only and no write operations are allowed ( No need to modify )**



![](https://img-blog.csdnimg.cn/20201224111746884.png#pic_center)

版权声明
本文为[Technical house Xiaobai]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224163424917O.html

Scroll to Top