{{π Type Talent Training Plan}} Redis Command Document

Redis

installation

Unzip the redis compressed package

Enter the redis source code package.

Execute make, if a fatal error occurs. Execute make MALLOC=libc

Installation execution make install PREFIX=/usr/redis Installed in the /usr/redis folder

use

  1. Enter the redis/bin directory and execute./redis-server to open the redis service
  2. Connect to redis ./redis-cli -p 6379 -h 127.0.0.1
  3. Set key value
  4. Query get key
  5. Redis has a total of 16 libraries from 0-15. Available select number to choose.
  6. Clear the current library FLUSHDB Clear all the libraries FLUSHALL

key command

  1. Exclusion key del key1 key2 key3…
  2. View all key keys *
  3. Determine whether the key exists exists key
  4. Set the key timeout time expire key seconds or pexpire key milliseconds
  5. Move key to the specified library number move key library number
  6. Returns the remaining production time ttl key or pttl key of the key. The former returns seconds, the latter returns milliseconds
  7. Random return a key randomkey
  8. Rename key rename key new name
  9. The type used to view the value of the key type key

String type

  1. Set multiple key values ​​mset key value key value key value. . .
  2. Get the value of multiple keys mget key key key. . .
  3. Get the original value of the key and assign the new value to the new value of getset key
  4. Get the length of the key value strlen key
  5. Append content to the value of key append key Append content
  6. Intercept the content of the key value getrange key 0 3
  7. Set the key and set the timeout time for the key setex key seconds or psetex key milliseconds
  8. Do nothing if it exists, and create a key value setnx key value if it does not exist
  9. Set multiple key values ​​at the same time, if one exists, do nothing. msetnx key value key value key value. . .
  10. If the value of the key is a numeric string, subtract one decr key or subtract the specified value decrby key to specify the number
  11. If the key value is a numeric string, add an incr key or add a specified value incrby key to specify a number
  12. The value of the key is a numeric string plus a floating point number incrbyfloat key specifies a floating point number

list type

  1. Create a set lpush key value value value or rpush key value value value
  2. Traverse a set lrange key 0 -1
  3. Add value lpushx key value or rpushx key value value to an existing collection
  4. Delete an element from the left of the collection lpop key
  5. Delete an element rpop key from the right side of the collection
  6. Query the length of the collection llen key
  7. Modify the value of the element in the set lset key index number new value
  8. Get the lindex key index number of the specified element in the collection
  9. Delete duplicate elements in the collection lrem key Delete several element names
  10. Keep the elements of a certain interval in the set ltrim key 2 4
  11. Insert an element before an element in the collection linsert key before the value inserted by the coordinate element
  12. Insert an element after an element in the collection linsert key after the value inserted by the coordinate element

set type

  1. Create a set collection sadd key value value value. . .
  2. View all elements smembers key in the set collection
  3. See how many elements in the set collection scar key
  4. Randomly delete and return the number of spop keys in the set collection
  5. Move an element from a set collection to another set collection remove key1 key2 element name
  6. Delete the srem key value value of the element in the set collection
  7. Check whether there is an element sismember key element name in the set collection
  8. Randomly returns the number of elements srandmember key in the set collection
  9. The key1 collection is compared with the subsequent collections, the repeated elements are removed, and the remaining elements in the key1 collection are returned after the comparison. sdiff key1 key2 key3
  10. Find the intersection of several sets sinter key1 key2 key3
  11. Find the sum of several sets sunion key1 key2 key3

zset type

  1. Create a set zadd key score value score value
  2. Query the value within the score range in the collection zrangebyscore key 0 100
  3. Traverse the values ​​in the set zrange key 0 -1 [withscores]
  4. Query the number of elements in the collection zcard key
  5. View the ranking of the element in the collection zrank key element name
  6. View the reverse ranking zrevrank key element name
  7. View the score of the element zscore key element name
  8. Remove elements from the collection zrem key element name element name
  9. Add points to an element zincrby key score element name

hash type

  1. Create a collection hset key kv
  2. Get the value of a key in the collection hget key k
  3. Get all the key values ​​in the collection hgetall key
  4. Delete the key value hdel key k in the set
  5. Determine whether the keys in the set exist hexists key k
  6. Get all the keys in the collection hkeys key
  7. Get all the values ​​in the collection hvals key
  8. Add multiple keys to hmset key kvkvkv
  9. Get multiple values ​​in the collection hmget key kkk
  10. Set a non-existent key hsetnx key kv to the collection
  11. Add a value hincrby key k to the value of the key in the collection
  12. Add a floating-point value to the value of the key in the collection hincrbyfloat key k floating-point value

detail

The default port of redis is 6379

How to modify the port number, you need to import the redis configuration file. Copy redis.conf in the source package to /bin in the installation directory.

Vim edit this file and modify the port number. Load the configuration file at startup to take effect. ./redis-server redis.conf

Then when connecting to redis./redis-cli -p port number

There are 16 libraries by default in redis. 0-15

How to modify the number of libraries. Just modify the value of databases in the configuration file.

redis runs in the background

Modify the daemonize to yes in the configuration file.

Redis visualization tool

Need to enable remote access permissions for redis. Modifying the configuration file bind to 0.0.0.0 means that all clients can access it.

Persistence mechanism

There are two persistence mechanisms in redis.

Snapshot persistence (snapshotting)

Save the state of redis at a certain moment to the hard disk in the form of a snapshot, the snapshot file is dump.rdb

You can modify the dbfilename in the configuration file to modify the name. dir can modify the RDB file generation path

Create a snapshot:

  1. Use the bgsave command.
  2. Use the save command. However, no commands can be executed until the snapshot is created.
  3. Use the shutdown command, redis executes the save command once and then shuts down the service
  4. Automatically produce snapshots based on configuration files. Bgsave is automatically executed after satisfying the conditions of the save item in the configuration file.

AOF (append only file) persistence

Redis saves all write commands in a file. If the data is lost, re-execute this file. Then it can be guaranteed that most of the data will be restored. But AOF is not turned on by default.

The configuration file needs to be changed to enable AOF. Appendonly yes is fine. The file name is appendonly.aof. The generation location is the same as the snapshot location. Just modify the dir item.

AOF synchronization frequency:

always: Every write command must be synchronized to the file, but this will greatly reduce the efficiency of redis

everysec: Synchronize once every second.

no: The system decides when to synchronize.

To modify the write frequency, modify the appendfsync item in the configuration file. Suggestion: The default is fine.

Redis' AOF rewrite mechanism

Rewrite (compress) the existing AOF file, thereby reducing the size of the AOF file.

Perform rewrite:

  1. Use the command bgrewriteaof
  2. Automatically rewrite and modify the configuration file. auto-aof-rewrite-percentage item

java operation redis

First introduce the jar package jedis.jar.

Create a redis client. Use the client object to call instructions to operate redis.

Springboot integrates springdata to operate redis

Introduce dependency spring-boot-starter-data-redis

Configure springboot configuration file

Required jar

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
        	<groupId>org.springframework.boot</groupId>
        	<artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

Custom annotation

//添加缓存
@Target(ElementType.METHOD)//声明注解使用的位置
@Retention(RetentionPolicy.RUNTIME)
public @interface SaveRedisCache {
	//可以加属性
    //public String/int/... value();
}
//移除缓存
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RemoveRedisCache {
    //可以加属性
    //public String/int/... value();
}


   切方法:
   
   @Configuration
   @Aspect//声明当前类是一个切面供容器读取
   public class RedisCache {
       @Autowired
       private RedisTemplate redisTemplate;
       @Autowired
       private StringRedisTemplate stringRedisTemplate;
   
       @Around("execution(* com.baizhi.service.*.select*(..))")
       public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
           RedisSerializer stringSerializer = new StringRedisSerializer();
           redisTemplate.setKeySerializer(stringSerializer);
           redisTemplate.setHashKeySerializer(stringSerializer);
           StringBuilder sb = new StringBuilder();
           //获取类名
           String className = proceedingJoinPoint.getTarget().getClass().getName();
           sb.append(className);
           //获取方法名
           String methodName = proceedingJoinPoint.getSignature().getName();
           sb.append(methodName);
           //获取所有的参数
           Object[] args = proceedingJoinPoint.getArgs();
           for (Object arg : args) {
               sb.append(arg);
           }
           String s = sb.toString();
           ValueOperations valueOperations = redisTemplate.opsForValue();
           Object result = null;
           if(redisTemplate.hasKey(s)){
               result = valueOperations.get(s);
           }else{
               result = proceedingJoinPoint.proceed();
               valueOperations.set(s,result);
   
           }
           return result;
       }
   
       @After("execution(* com.baizhi.service.*.delete*(..))")
       public void after(JoinPoint joinPoint){
           Set<String> keys = stringRedisTemplate.keys("*");
           for (String key : keys) {
               stringRedisTemplate.delete(key);
           }
       }
note:

​ It is found that the key value appears \xac\xed\x00\x05t\x00\tb, the default serialization method of redisTemplate is jdkSerializeable, and the default serialization method of StringRedisTemplate is StringRedisSerializer

Custom annotation based on cut

Add cache for read operations

@Configuration//当前类为配置类
@Aspect//作用是把当前类标识为一个切面供容器读取
public class RedisCache {
    @Autowired
    private RedisTemplate redisTemplate;
    @Around("@annotation(com.baizhi.annotation.SaveRedisCache)")
    public Object arround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        StringBuilder sb = new StringBuilder();
        //获取类名
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        //获取方法名
        String methodName = proceedingJoinPoint.getSignature().getName();
        sb.append(methodName);
        //获取所有的参数
        Object[] args = proceedingJoinPoint.getArgs();
        for (Object arg : args) {
            sb.append(arg);
        }
        String s = sb.toString();
        HashOperations hashOperations = redisTemplate.opsForHash();
        Boolean aBoolean = redisTemplate.hasKey(className);
        Object result = null;
        if(aBoolean){
            result = hashOperations.get(className,s);
        }else {
            result = proceedingJoinPoint.proceed();
            HashMap<String, Object> map = new HashMap<>();
            map.put(s, result);
            hashOperations.putAll(className, map);
            redisTemplate.expire(className,10, TimeUnit.SECONDS);
        }
        return  result;
    }

​ 2. The write operation needs to clear the cache

	@After("@annotation(com.baizhi.annotation.RemoveRedisCache)")
    public void after(JoinPoint joinPoint){
        String className = joinPoint.getTarget().getClass().getName();
        redisTemplate.delete(className);
    }