Redis transaction, Jedis, and redis Conf detailed explanation

affair

Essence of redis transaction: a set of commands!
All commands in a transaction will be serialized and executed in sequence during transaction execution!
Characteristics: disposable, sequential, exclusive

Redis ensures atomicity of a single command, but transactions do not guarantee atomicity

Three phases of a transaction:

  1. Start transaction (multi)
  2. Order queue (...)
  3. Execute transaction (exec)
127.0.0.1:6379> multi						#Open transaction
OK
#Order to join the team
127.0.0.1:6379> set k1 v1
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> get k2
QUEUED
127.0.0.1:6379> set k3 v3
QUEUED
127.0.0.1:6379> exec						#Execute transaction
1) OK
2) OK
3) "v2"
4) OK

Or cancel the transaction (DISCARD)

127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k4 v4
QUEUED
127.0.0.1:6379> DISCARD
OK
127.0.0.1:6379> get k4
(nil)

Compiled exception (command error), all commands in the transaction will not be executed

127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k1 v1
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> set k3 v3
QUEUED
127.0.0.1:6379> getset k7								#Wrong command, the whole transaction will not be executed
(error) ERR wrong number of arguments for 'getset' command
127.0.0.1:6379> set k4 v4
QUEUED
127.0.0.1:6379> set k5 v5
QUEUED
127.0.0.1:6379> exec
(error) EXECABORT Transaction discarded because of previous errors.
127.0.0.1:6379> get k4
(nil)

Runtime exception,
(if a command in the transaction queue makes an error while running, the error command throws an exception, and other commands execute normally)

127.0.0.1:6379> clear
127.0.0.1:6379> set k1 v1
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> incr k1
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> get k1
QUEUED
127.0.0.1:6379> get k2
QUEUED
127.0.0.1:6379> exec
1) (error) ERR value is not an integer or out of range
2) OK
3) "v1"
4) "v2"

monitor! Watch

**Pessimistic lock: * * it will be locked every time you get the data

**Optimistic lock: * * it will not be locked every time you go to get the data. However, when updating, we will judge whether others have updated this data during this period.

redis monitoring test

Under normal circumstances

127.0.0.1:6379> set money 100
OK
127.0.0.1:6379> set out 0
OK
127.0.0.1:6379> watch money
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> DECRBY money 20
QUEUED
127.0.0.1:6379> INCRBY out 20
QUEUED
127.0.0.1:6379> exec
1) (integer) 80
2) (integer) 20
127.0.0.1:6379> WATCH money
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> DECRBY money 10
QUEUED
127.0.0.1:6379> INCRBY out 10
QUEUED
====================================               At this time, it is modified in another client money Value of
127.0.0.1:6379> exec							   Submit failed
(nil)

====================================         	   Solution: Unlock first and then lock
127.0.0.1:6379> UNWATCH 						   # Abandon surveillance
OK
127.0.0.1:6379> watch money
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> decrby money 20
QUEUED
127.0.0.1:6379> incrby out 20
QUEUED
127.0.0.1:6379> exec # success!
1) (integer) 180
2) (integer) 40

Therefore, optimistic locking can be realized by using watch

Jedis

Jedis: using Java to operate Redis

Jedis is a Java connection development tool officially recommended by Redis! Use java to operate Redis middleware! If you want to use java to operate Redis, you should be very familiar with jedis.

test

  1. Import corresponding dependencies
	<dependencies>
        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.3.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>
    </dependencies>
  1. Coding test:
    -Connect database
    -Operation command
    -Disconnect
package cn.lvziwei;

import redis.clients.jedis.Jedis;

/**
 * @Author lvziwei
 * @Create 2021/2/11 17:14
 */
public class TestPing {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1",6379);
        System.out.println(jedis.ping());
    }
}

Output result:

Command for key operation

public class TestPing {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1",6379);
        System.out.println("Clear data:"+jedis.flushDB());
        System.out.println("judge username Is there:"+jedis.exists("username"));
        System.out.println("newly added<'username','lvziwei'>Key value pairs:"+jedis.set("username", "lvziwei"));
        System.out.println("newly added<'password','password'>Key value pairs:"+jedis.set("password", "password"));
        System.out.print("All keys in the system are as follows:");
        Set<String> keys = jedis.keys("*");
        System.out.println(keys);
        System.out.println("Delete key password:"+jedis.del("password"));
        System.out.println("Judgment key password Is there:"+jedis.exists("password"));
        System.out.println("View key username Type of value stored:"+jedis.type("username"));
        System.out.println("Random return key A of space:"+jedis.randomKey());
        System.out.println("rename key: "+jedis.rename("username","name"));
        System.out.println("Take out the modified name: "+jedis.get("name"));
        System.out.println("Query by index:"+jedis.select(0));
        System.out.println("Delete all in the currently selected database key: "+jedis.flushDB());
        System.out.println("Return to the current database key Number of:"+jedis.dbSize());
        System.out.println("Delete all in all databases key: "+jedis.flushAll());
    }
}

Operation results:

Command for String operation

public class TestPing {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1",6379);
        jedis.flushDB();
        System.out.println("===========Add data===========");
        System.out.println(jedis.set("key1","value1"));
        System.out.println(jedis.set("key2","value2"));
        System.out.println(jedis.set("key3", "value3"));
        System.out.println("Delete key key2:"+jedis.del("key2"));
        System.out.println("Get key key2:"+jedis.get("key2"));
        System.out.println("modify key1:"+jedis.set("key1", "value1Changed"));
        System.out.println("obtain key1 Value of:"+jedis.get("key1"));
        System.out.println("stay key3 Add value after:"+jedis.append("key3", "End"));
        System.out.println("key3 Value of:"+jedis.get("key3"));
        System.out.println("Add multiple key value pairs:"+jedis.mset("key01","value01","key02","value02","key03","value03"));
        System.out.println("Get multiple key value pairs:"+jedis.mget("key01","key02","key03"));
        System.out.println("Get multiple key value pairs:"+jedis.mget("key01","key02","key03","key04"));
        System.out.println("Delete multiple key value pairs:"+jedis.del("key01","key02"));
        System.out.println("Get multiple key value pairs:"+jedis.mget("key01","key02","key03"));
        jedis.flushDB();
        System.out.println("===========Adding a key value pair prevents overwriting the original value==============");
        System.out.println(jedis.setnx("key1", "value1"));
        System.out.println(jedis.setnx("key2", "value2"));
        System.out.println(jedis.setnx("key2", "value2-new"));
        System.out.println(jedis.get("key1"));
        System.out.println(jedis.get("key2"));
        System.out.println("===========Add key value pairs and set effective time=============");
        System.out.println(jedis.setex("key3", 2, "value3"));
        System.out.println(jedis.get("key3"));
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(jedis.get("key3"));
        System.out.println("===========Get the original value and update it to the new value==========");
        System.out.println(jedis.getSet("key2", "key2GetSet"));
        System.out.println(jedis.get("key2"));
        System.out.println("get key2 String of values:"+jedis.getrange("key2", 2, 4));
    }
}

Operation results:

Operation command on List

public class TestPing {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1",6379);
        jedis.flushDB();
        System.out.println("===========Add a list===========");
        jedis.lpush("collections", "ArrayList", "Vector", "Stack",
                "HashMap", "WeakHashMap", "LinkedHashMap");
        jedis.lpush("collections", "HashSet");
        jedis.lpush("collections", "TreeSet");
        jedis.lpush("collections", "TreeMap");
        System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));
        //-1 represents the penultimate element, - 2 represents the penultimate element, and end is - 1 to query all
        System.out.println("collections Interval 0-3 Elements of:"+jedis.lrange("collections",0,3));
        System.out.println("===============================");
        // Delete the value specified in the list. The second parameter is the number of deleted values (when there are duplicates). The value add ed later is deleted first, which is similar to out of the stack
        System.out.println("Delete the specified number of elements:"+jedis.lrem("collections", 2, "HashMap"));
        System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));
        System.out.println("Delete table 0 below-3 Elements outside the interval:"+jedis.ltrim("collections", 0, 3));
        System.out.println("collections Content of:"+jedis.lrange("collections", 0, -1));
        System.out.println("collections List out of stack (left end):"+jedis.lpop("collections"));
        System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));
        System.out.println("collections Add elements from the right end of the list, and lpush Corresponding:"+jedis.rpush("collections", "EnumMap"));
        System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));
        System.out.println("collections List out of stack (right end):"+jedis.rpop("collections"));
        System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));
        System.out.println("modify collections Specify the contents of subscript 1:"+jedis.lset("collections", 1, "LinkedArrayList"));
        System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));
        System.out.println("===============================");
        System.out.println("collections Length of:"+jedis.llen("collections"));
        System.out.println("obtain collections Elements with subscript 2:"+jedis.lindex("collections", 2));
        System.out.println("===============================");
        jedis.lpush("sortedList", "3","6","2","0","7","4");
        System.out.println("sortedList Before sorting:"+jedis.lrange("sortedList", 0, -1));
        System.out.println(jedis.sort("sortedList"));
        System.out.println("sortedList After sorting:"+jedis.lrange("sortedList", 0, -1));
    }
}

Operation results:

Operation command for Set

public class TestPing {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.flushDB();
        System.out.println("============Add elements to the collection (no duplicates)============");
        System.out.println(jedis.sadd("eleSet", "e1","e2","e4","e3","e0","e8","e7","e5"));
        System.out.println(jedis.sadd("eleSet", "e6"));
        System.out.println(jedis.sadd("eleSet", "e6"));
        System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet"));
        System.out.println("Delete an element e0: "+jedis.srem("eleSet", "e0"));
        System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet"));
        System.out.println("Delete two elements e7 and e6: "+jedis.srem("eleSet", "e7","e6"));
        System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet"));
        System.out.println("Remove a random element from the set:"+jedis.spop("eleSet"));
        System.out.println("Randomly remove an element from the collection:"+jedis.spop("eleSet"));
        System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet"));
        System.out.println("eleSet Number of elements contained in:"+jedis.scard("eleSet"));
        System.out.println("e3 Is it eleSet Medium:"+jedis.sismember("eleSet", "e3"));
        System.out.println("e1 Is it eleSet Medium:"+jedis.sismember("eleSet", "e1"));
        System.out.println("e1 Is it eleSet Medium:"+jedis.sismember("eleSet", "e5"));
        System.out.println("=================================");
        System.out.println(jedis.sadd("eleSet1", "e1","e2","e4","e3","e0","e8","e7","e5"));
        System.out.println(jedis.sadd("eleSet2", "e1","e2","e4","e3","e0","e8"));
        System.out.println("take eleSet1 Delete in e1 And deposit eleSet3 Medium:"+jedis.smove("eleSet1", "eleSet3", "e1"));//Move to collection element
        System.out.println("take eleSet1 Delete in e2 And deposit eleSet3 Medium:"+jedis.smove("eleSet1", "eleSet3", "e2"));
        System.out.println("eleSet1 Elements in:"+jedis.smembers("eleSet1"));
        System.out.println("eleSet3 Elements in:"+jedis.smembers("eleSet3"));
        System.out.println("============Set operation=================");
        System.out.println("eleSet1 Elements in:"+jedis.smembers("eleSet1"));
        System.out.println("eleSet2 Elements in:"+jedis.smembers("eleSet2"));
        System.out.println("eleSet1 and eleSet2 Intersection of:"+jedis.sinter("eleSet1","eleSet2"));
        System.out.println("eleSet1 and eleSet2 Union of:"+jedis.sunion("eleSet1","eleSet2"));
        System.out.println("eleSet1 and eleSet2 Difference set of:"+jedis.sdiff("eleSet1","eleSet2"));//There are in eleSet1 and not in eleSet2
        jedis.sinterstore("eleSet4","eleSet1","eleSet2");//Find the intersection and save the intersection to the set of dstkey
        System.out.println("eleSet4 Elements in:"+jedis.smembers("eleSet4"));
    }
}

Operation results:

Operation commands for Hash

public class TestPing {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.flushDB();
        Map<String,String> map = new HashMap<>();
        map.put("key1","value1");
        map.put("key2","value2");
        map.put("key3","value3");
        map.put("key4","value4");
//Add a hash element named hash (key)
        jedis.hmset("hash",map);
//Add an element with key as key5 and value as value5 to the hash named hash
        jedis.hset("hash", "key5", "value5");
        System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash"));//return Map<String,String>
        System.out.println("hash hash All keys for are:"+jedis.hkeys("hash"));//return Set<String>
        System.out.println("hash hash All values for are:"+jedis.hvals("hash"));//return List<String>
        System.out.println("take key6 Add an integer to the saved value if key6 Add if it does not exist key6: "+jedis.hincrBy("hash", "key6", 6));
        System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash"));
        System.out.println("take key6 Add an integer to the saved value if key6 Add if it does not exist key6: "+jedis.hincrBy("hash", "key6", 3));
        System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash"));
        System.out.println("Delete one or more key value pairs:"+jedis.hdel("hash", "key2"));
        System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash"));
        System.out.println("hash hash Number of middle key value pairs:"+jedis.hlen("hash"));
        System.out.println("judge hash Exists in key2: "+jedis.hexists("hash","key2"));
        System.out.println("judge hash Exists in key3: "+jedis.hexists("hash","key3"));
        System.out.println("obtain hash Values in:"+jedis.hmget("hash","key3"));
        System.out.println("obtain hash Values in:"+jedis.hmget("hash","key3","key4"));
    }
}

Operation results:

affair

public class TestTX {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.flushDB();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello","world");
        jsonObject.put("name","lvziwei");

        Transaction multi = jedis.multi();
        String result = jsonObject.toJSONString();

        try {
            multi.set("user1",result);
            multi.set("user2",result);
            int i = 1/0;    //abnormal
            multi.exec();
        } catch (Exception exception) {
            exception.printStackTrace();
            multi.discard();
        } finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close();
        }

    }
}

Operation results:

Redis.conf detailed explanation

Company


The configuration file unit is not case sensitive

contain


Import other profiles

network

bind 127.0.0.1 					# Bound ip
protected-mode yes 				# Protection mode
port 6379 						# Default port

currency

daemonize yes # By default, Redis does not run as a daemon. If it needs to be turned on, change to yes
supervised no # Redis daemon can be managed through upstart and systemd
pidfile /var/run/redis_6379.pid # To run redis in the background process mode, you need to specify the pid file
loglevel notice # Log level. Options are:
				# debug (record a large amount of log information, which is suitable for development and testing);
				# verbose (more log information);
				# notice (appropriate amount of log information, used in the production environment);
				# warning (only some important and key information will be recorded).
logfile "" # The location of the log file, when specified as an empty string, is standard output
databases 16 # Set the number of databases. The default database is DB 0
always-show-logo yes # Always show logo

Snapshapting snapshot

# At least one key value changes within 900 seconds (15 minutes) (database saving - persistence)
save 900 1
# At least 10 key values change within 300 seconds (5 minutes) (database saving - persistence)
save 300 10
# At least 10000 key values change within 60 seconds (1 minute) (then save the database -- persist)
save 60 10000
stop-writes-on-bgsave-error yes # Do you want to continue working after persistent errors occur
rdbcompression yes # Use compressed rdb files yes: compressed, but requires some cpu consumption. No: no pressure
 Shrinking requires more disk space
rdbchecksum yes # Whether to check the rdb file is more conducive to the fault tolerance of the file, but when saving the rdb file
 Wait, there will be about 10%Performance loss of
dbfilename dump.rdb # dbfilenamerdb file name
dir ./ # dir data directory, where the database will be written. rdb and aof files will also be written in this directory

REPLICATION replication

We'll talk about master-slave replication later, and then explain it to you! Skip here first!

SECURITY security

View, set and cancel access password

# Start redis
# Connect client
# Get and set password
config get requirepass
config set requirepass "123456"

limit

maxclients 10000 # Set the maximum number of client connections that can be connected to redis
maxmemory <bytes> # Maximum memory capacity of redis configuration
maxmemory-policy noeviction # Maxmemory policy processing policy when the memory reaches the maximum limit
				#Volatile LRU: use the LRU algorithm to remove the key that has set the expiration time.
				#Volatile random: randomly remove the key s whose expiration time has been set.
				#Volatile TTL: remove key s that are about to expire and delete them according to the latest expiration time (supplemented by TTL)
				#Allkeys LRU: use LRU algorithm to remove any key.
				#All keys random: remove any keys randomly.
				#noeviction: no key is removed, but a write error is returned.

append only mode

appendonly no # Whether the append only mode is used as the persistence mode. By default, the rdb mode is used for persistence. This mode is sufficient in many applications

appendfilename "appendonly.aof"  #The name of the persistent file

appendfsync always 				#sync is for every modification. Consumption performance
appendfsync everysec			#If sync is executed every second, this 1s data may be lost
appendfsync no					#When sync is not executed, the operating system synchronizes the data itself, which is the fastest

Tags: Redis

Posted by pocobueno1388 on Tue, 19 Apr 2022 07:31:21 +0930