0

Nghiên cứu transaction Redis trong Spring Boot

Transaction trong Redis hoạt động giống một hàng đợi: các lệnh được đưa vào queue trước, sau đó mới được thực thi. Toàn bộ quá trình gồm ba bước:

  1. Bắt đầu transaction
  2. Đưa các lệnh vào hàng đợi
  3. Thực thi transaction

Các lệnh dùng trong bài như sau:

Lệnh Mô tả
MULTI Bắt đầu một transaction
EXEC Commit transaction
DISCARD Hủy transaction — các lệnh đã vào hàng đợi sẽ không được thực thi
WATCH Theo dõi một hoặc nhiều key. Nếu key đang được theo dõi bị lệnh khác thay đổi trước khi transaction được commit, transaction hiện tại sẽ thất bại
UNWATCH Bỏ theo dõi các key

Dưới đây, chúng ta dùng một ví dụ Spring Boot để làm rõ ý nghĩa các lệnh trên:

package com.test.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class TestSpringApplication {
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@RequestMapping("/exec1")
	public String test1(){
		stringRedisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				connection.multi();
				connection.commands().set("k1".getBytes(),"1".getBytes());
				connection.commands().set("k2".getBytes(),"2".getBytes());
				connection.exec();
				return true;
			}
		});

		return "k1="+stringRedisTemplate.opsForValue().get("k1")+",k2="+stringRedisTemplate.opsForValue().get("k2");
	}
	@RequestMapping("/exec2")
	public String exec2(){

		try{
			stringRedisTemplate.execute(new RedisCallback<Boolean>() {
				private int i=0;
				@Override
				public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
					connection.multi();
					connection.commands().set("k1".getBytes(),"11".getBytes());
					connection.commands().set("k2".getBytes(),"22".getBytes());
					if(i==0){
						throw new RedisSystemException("Một exception",new RuntimeException("1"));
					}
					connection.exec();
					return true;
				}
			});
		}catch (Exception e){
			e.printStackTrace();
		}
		return "k1="+stringRedisTemplate.opsForValue().get("k1")+",k2="+stringRedisTemplate.opsForValue().get("k2");
	}

	@RequestMapping("/discard")
	public String discard(){
		try{
			stringRedisTemplate.execute(new RedisCallback<Boolean>() {
				@Override
				public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
					connection.multi();
					connection.commands().set("k3".getBytes(),"3".getBytes());
					connection.commands().set("k4".getBytes(),"4".getBytes());
					connection.discard();
					connection.exec();
					return true;
				}
			});
		}catch (Exception e){
			e.printStackTrace();
		}

		return "k3="+stringRedisTemplate.opsForValue().get("k3")+",k4="+stringRedisTemplate.opsForValue().get("k4");
	}
	@RequestMapping("/watch1")
	public String watch1(){
		// Khởi chạy một thread
		new Thread(()->{
			stringRedisTemplate.execute(new RedisCallback<Boolean>() {
				@Override
				public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
					try {
						connection.watch("k5".getBytes());
						connection.multi();
						connection.commands().set("k5".getBytes(), "5".getBytes());
						// Tạm dừng 5 giây rồi mới commit transaction
						try {
							Thread.sleep(5000);
						} catch (InterruptedException e) {
						}
						connection.exec();
					}catch (Exception e){
						e.printStackTrace();
					}

					return true;
				}
			});
		}).start();

		// Khởi chạy một thread
		new Thread(()->{
			stringRedisTemplate.execute(new RedisCallback<Boolean>() {
				@Override
				public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
					try {
						connection.multi();
						connection.commands().set("k5".getBytes(), "55".getBytes());
						connection.exec();
					}catch (Exception e){
						e.printStackTrace();
					}
					return true;
				}
			});
		}).start();
		return "success";
	}
	@RequestMapping("/watch2")
	public String watch2(){
		return "k5="+stringRedisTemplate.opsForValue().get("k5");
	}
	public static void main(String[] args) {
		SpringApplication.run(TestSpringApplication.class, args);
	}

}
  1. exec1 Đây là trường hợp bình thường. Dùng curl để test, kết quả trả về: k1=1,k2=2
  2. exec2 Chúng ta cố ý ném exception khi các lệnh vừa được đưa vào hàng đợi (chưa EXEC). Các lệnh set sẽ không có hiệu lực; kết quả test vẫn là: k1=1,k2=2
  3. discard Minh họa việc hủy transaction: gọi DISCARD trước, rồi mới EXEC. Server sẽ báo lỗi ERR EXEC without MULTI, cho thấy các lệnh set đã không được thực hiện.
  4. watch1 và watch2 Chúng ta mô phỏng hai thread chạy song song. Thread 1 theo dõi key rồi chờ 5 giây; trong lúc đó thread 2 sửa ngay key này. Hết 5 giây, thread 1 mới commit thì transaction đã mất hiệu lực. Gọi watch2 để đọc giá trị, kết quả là k5=55 — transaction của thread 1 đã thất bại.

Cuối cùng về UNWATCH: mỗi khi gọi exec(), tầng client bên dưới sẽ tự động gọi UNWATCH, nên chúng ta không cần tự gọi lệnh này.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí