Redis (2) Operation of transactions and Jedis

Table of Contents of Series Articles

Notes on getting started with Redis (1): Redis installation and eight major data types under Linux



Preface

The essence of Redis transactions: a set of commands
Characteristics of transactions in Redis:

 Redis的单条命令式保存原子性的,但是事务不保证原子性,
 redis事务在执行过程中如果有一条命令执行失败,那么其后的命令仍然可以执行,不会回滚。
 事务没有隔离级别的概念。
 一个事务中所有的命令都会被序列化,在事务执行过程中,会按照顺序执行,
 所有的命令在事务中并没有直接被执行,发起执行时才会执行

Redis operates on transactions

Start a transaction:multi

insert image description here
Imperatives are executed in the order they are enqueued.

Execute transaction:exec

insert image description here
After the transaction is executed once, it is cleared.

Abandon transaction:discard

insert image description here

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

insert image description here

Runtime exception (other commands still run normally)

incr key If the key does not exist, it will be initialized to 0 by default, and then incr will be incremented by one.
insert image description here
Although the first command reported an error, other commands were still executed normally and successfully.

Pessimistic locking and optimistic locking

悲观锁:悲观锁总是假设最坏的情况,认为共享资源每次被访问的时候就会出现问题(比如共享数据被修改),
       所以每次在获取资源操作的时候都会上锁,这样其他线程想拿到这个资源就会阻塞直到锁被上一个持有者释放。
       也就是说,共享资源每次只给一个线程使用,其它线程阻塞,用完后再把资源转让给其它线程。
乐观锁:乐观锁总是假设最好的情况,认为共享资源每次被访问的时候不会出现问题,
  • Pessimistic locks are usually used when there are many writes (multiple write scenarios, fierce competition), so as to avoid frequent failures and retries affecting performance, and the overhead of pessimistic locks is fixed.
  • Optimistic locking is usually more common than in situations where there are fewer writes (multi-read scenarios, less competition), which can avoid frequent locking that affects performance. However, optimistic locking mainly targets a single shared variable.

redis watchcomes with pessimistic lock

This is the output of normal execution.
insert image description here
Before the transaction is executed,
insert image description here
the watch instruction in redis that changes the data is similar to an optimistic lock. When the transaction is committed, if the value of any KEY among the multiple KEYs monitored by the watch has been changed by other clients, use EXEC When executing a transaction, the transaction queue will not be executed, and a Nullmulti-bulk response will be returned to notify the caller that the transaction execution failed.
unwatch cancels monitoring and regains value
insert image description here

Use Java to operate Redis

Jedis是Redis官方推荐使用的Java连接redis的客户端。

Guide dependencies:

 <!--导入jredis的包-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.2.0</version>
        </dependency>
        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>

Test whether you can ping

import redis.clients.jedis.Jedis;
public class RedisTest {
    
    
    public static void main(String[] args) {
    
    
        Jedis jedis = new Jedis("192.168.200.200",6379);
        String ping = jedis.ping();
        System.out.println(ping);
    }
}

Solve Jedis connection failure problem

1. Turn off the firewall:
systemctl status firewalld Check the status of the firewall.
systemctl stop firewalld Turn off the firewall
. 2. Confirm that Linux and Windows can ping.
insert image description hereinsert image description here

If you still get an error
insert image description here3. Modify redis.conf.
By default, bind 127.0.0.1 only accepts local access
insert image description here
. When protected-mode is enabled, if no bind and password are set, only local access is accepted.

insert image description herepass!

insert image description here

Jedis operation transaction

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
public class RedisTest {
    
    
    public static void main(String[] args) {
    
    
        Jedis jedis = new Jedis("192.168.31.238",6379);
        jedis.flushDB();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello", "world");
        jsonObject.put("name", "liu heng");
       // 开启事务
        Transaction multi = jedis.multi();
        String result = jsonObject.toJSONString();
       // jedis.watch(result)
        try {
    
    
        multi.set("user1", result);
        multi.set("user2", result);
        // 执行事务
        multi.exec();
          }catch (Exception e){
    
    
        // 放弃事务
             multi.discard();
          } finally {
    
    
        // 关闭连接
           System.out.println(jedis.get("user1"));
           System.out.println(jedis.get("user2"));
           jedis.close();
     }
   }

 }

insert image description here

Guess you like

Origin blog.csdn.net/qq_45637894/article/details/130771737