Introduction to Redis and Simple Operations

Keywords: Jedis Redis Database C

Introduction to Redis

  • Redis is a key-value-oriented memory database for data types, which can meet our needs for fast reading and writing of massive data.
  • Is a nosql non-relational database
  • Redis keys can only be string-type values that can be of many data types
    • String string
    • Hash hash
    • List string list
    • Set string set
    • sorted set ordered string set
  • Characteristics of Redis
    • High Performance: Reading 11w/s and writing 8.1w/s is a single-threaded service
    • Atomicity: Ensuring Data Accuracy
    • Persistent storage: (RDB snapshots, AOF logs)
    • Master-slave structure
    • After Cluster Support 3.0
  • Application scenarios
    • Take Sina Weibo as an example
    • hash Focus List, Fan List, etc.
    • Number of String Weibo Fans
    • sorted set popular microblogs, TopN
  • Note: Redis is written in c language. Before installing Redis, we need to configure the compilation environment of c language.
  • Basic instructions of Redis
    • keys?* []? Wait to see if key is disabled in a regular production environment
    • exists key determines whether a key exists
    • del key1 key2... Delete key-value pairs
    • help View help
    • Qut / exit exit exit exit client
    • Note: Redis commands are case-insensitive
  • Characteristics of Redis database
    • Multi-database
      • Each database is named after an incremental number starting at 0. Customization is not supported.
      • Redis supports 16 databases by default, and you can modify the default by modifying the database parameter
      • Redis defaults to database 0
      • Select digits can select databases
      • Multiple databases are not completely isolated
      • flushall: Clear all data under the Redis instance
        • flushdb empties all data in the current database

Redis Common Data Types

String
  • String type is the most basic data type of Redis. It can store any form of data, including binary data and so on. The maximum storage capacity of a string-type value is 1GB

  • Add data

    • set k v

    • 127.0.0.1:6379> set k1 v1
      OK
      
    • Add more than one data at a time

    • mset k2 v2 k3 v3

    • 127.0.0.1:6379> mset k2 v2 k3 v3
      OK
      
  • get data

    • get k1

    • 127.0.0.1:6379> get k1
      "v1"
      
    • mget k2 k3

    • 127.0.0.1:6379> mget k2 k3
      1) "v2"
      2) "v3"
      
  • Increasing and Decreasing

    • incr Incremental Decrease

    • 127.0.0.1:6379> set num 1
      OK
      127.0.0.1:6379> incr num
      (integer) 2
      127.0.0.1:6379> decr num
      (integer) 1
      
  • Increase and decrease according to specified type

    • incrby Incremental Decrease by Decrease

    • 127.0.0.1:6379> incrby num 2
      (integer) 3
      127.0.0.1:6379> decrby num 2
      (integer) 1
      
    • Floating-point self-increasing can not be reduced by floating-point self-increasing

    • 127.0.0.1:6379> incrbyfloat num 1.1
      "2.1"
      127.0.0.1:6379> decrbyfloat num 1.1
      (error) ERR unknown command 'decrbyfloat'
      
  • Get Length

    • 127.0.0.1:6379> set k asdsad
      OK
      127.0.0.1:6379> get k
      "asdsad"
      127.0.0.1:6379> strlen k
      (integer) 6
      
hash
  • The value of hash type stores the mapping of field and field value. The field and field value can only be a string, and other data types are not supported. The number of hash keys can store 2 ^ 32-1 fields

  • Add data

    • 127.0.0.1:6379> hset user name zs
      (integer) 1
      127.0.0.1:6379> hmset users name ls age 18
      OK
      
  • get data

    • 127.0.0.1:6379> hget user name       Get the specified k Value
      "zs"
      127.0.0.1:6379> hmget users name age   Get the specified k Multiple values
      1) "ls"
      2) "18"
      127.0.0.1:6379> hlen users     Obtain k Quantity
      (integer) 2
      127.0.0.1:6379> hkeys users    Get all k
      1) "name"
      2) "age"
      127.0.0.1:6379> hvals users     Get all v
      1) "ls"
      2) "18"
      127.0.0.1:6379> hgetall users    Get all kv Yes
      1) "name"
      2) "ls"
      3) "age"
      4) "18"
      
  • Judging whether a key exists in a hash

    • 127.0.0.1:6379> hexists user name
      (integer) 1
      127.0.0.1:6379> hexists user age
      (integer) 0
      
  • Increase progressively

    • Hincrby hash type does not have hincr command
  • Delete data

    • hdel
List
  • Is an ordered list of string types. The internal implementation of the list is implemented using a two-way linked list.
    • Lists can also be used as queues, such as first in first out queues
    • A list-type key can hold up to 32-1 elements of 2.
  • Common instructions
    • lpush/rpush/lpop/rpop Add data from left/right and extract data from left/right
    • llen/lrange Gets the length of the list, Gets the value of the specified range of the list, Views all 0-1
    • lindex queries data at specified corner locations
    • lset Modifies the Value of the Specified Corner
set
  • All elements in a set set set are unreplicated and disordered
    • Keys of a collection type store up to 32-1 elements of 2
  • Common commands
    • sadd/smembers/srem/sismember
      • Adding elements to a collection to get the number of collection summary elements deleting elements with specified values in the collection does not exist, that is, deleting failed return value of 0 and successfully returning value of 1 to see if a specified value exists
    • sdiff difference set
    • sinter intersection
    • sunion union returns the result directly
    • sdiffstore/sinterstore/sunionstore results exist in another specified collection
    • scard gets the length of the collection
sorted set
  • Ordered sets associate a score for each element on the basis of the set, and according to the score, the elements with the highest score can be obtained by sorting.
  • Common instructions
    • zadd adds the value of the specified score to the specified key
    • zscore to see the score of the specified value
    • The first few scores obtained by zrange are small to large
    • zrevrange gets the first few points in reverse order to be small
    • zrangebyscore gets the specified element according to the score. By default, the closed interval can be used to use "(" to use the open interval.
    • Zicrby Specified Element Score Self-Increasing
    • zcard gets the number of elements in a set
    • zcount gets the elements within the specified score range
    • zrem deletes specified elements in a collection

Java Operation Redis

  • Simple single-machine connection

    • package jredistest.jredisa;
      
      import redis.clients.jedis.Jedis;
      /**
       * Simple single-machine connection
       * @author zhao
       *
       */
      public class RedisDemo01 {
      	public static void main(String[] args) {
      		Jedis jedis = new Jedis("192.168.32.110",6379);
      		
      		jedis.set("aaa", "111");
      		
      		String value =jedis.get("str1");
      		
      		System.out.println(value);
      		
      		jedis.close();	
      	}
      
      }
      
      
  • Connection pool connection

    • package jredistest.jredisa;
      
      import redis.clients.jedis.Jedis;
      import redis.clients.jedis.JedisPool;
      import redis.clients.jedis.JedisPoolConfig;
      
      
      /**
       * Single-machine connection pool
       * 
       * @author zhao
       *
       */
      public class jredisDeml {
      	public static void main(String[] args) {
      		//Configuration information of connection pool
      				JedisPoolConfig poolConfig = new JedisPoolConfig();
      				//Maximum number of idle connections in connection pool
      				poolConfig.setMaxIdle(10);
      				//Maximum number of connections allowed to be created in connection pool
      				poolConfig.setMaxTotal(100);
      				//Maximum waiting time for creating links
      				poolConfig.setMaxWaitMillis(2000);
      				//Represents that links are tested when they are removed from the connection pool to ensure that the extracted links are available.
      				poolConfig.setTestOnBorrow(true);
      				
      				//Get the connection pool
      				JedisPool jedisPool = new JedisPool(poolConfig, "192.168.32.110", 6379);
      				//Get a jedis link from the connection pool
      				Jedis jedis = jedisPool.getResource();
      				String value = jedis.get("str");
      				System.out.println(value);
      				//Return links to connection pools
      				jedis.close();
      				
      				//Close connection pool
      				jedisPool.close();
      				
      	}
      
      }
      
      package jredistest.jredisa;
      
      import redis.clients.jedis.Jedis;
      import redis.clients.jedis.JedisPool;
      import redis.clients.jedis.JedisPoolConfig;
      
      public class jidisTest1 {
      	private jidisTest1(){}
      	private static JedisPool jedisPool=null;
      	
      	/**
      	 * Getting connections from connection pools
      	 * @return
      	 */
      	public static synchronized Jedis getJedis() {
      		if(jedisPool==null) {			
      			JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
      			//Specifies the maximum number of empty connections in the connection pool
      			jedisPoolConfig.setMaxIdle(10);
      			//Specifies the maximum number of connections in the connection pool
      			jedisPoolConfig.setMaxTotal(100);
      			//Setting Maximum Connection Timeout
      			jedisPoolConfig.setMaxWaitMillis(2000);
      			
      			jedisPoolConfig.setTestOnBorrow(true);
      			
      			jedisPool = new JedisPool(jedisPoolConfig,"192.168.32.110",6379);
      			
      		}
      		return jedisPool.getResource();
      	}
      	/**
      	 * Return connection pool connection
      	 * @param jedis
      	 */
      	public static void returnResource(Jedis jedis) {
      		jedis.close();
      	}
      	/**
      	 * Close connection pool
      	 */
      	public static void closePool() {
      		jedisPool.close();
      	}
      	
      	
      
      }
      
      

Posted by billynastie on Mon, 09 Sep 2019 06:05:01 -0700