Redis的事务实际上是一条一条的排队命令,每条命令具有原子性,但是事务本身没有原子性,值得注意的是redis没有隔离级别一说。
//其中 multi 开启事务‘ exec 执行事务 DISCARD 取消事务
其中事务在运行的时候遇到了错误,其他正常的命令是可以执行的,这也是为什么Redis 中事务没有一致性一说,
乐观锁与悲观锁 悲观锁悲观锁是一种思想,悲观锁的设计目的是因为任何东西都有可能改变数据造成错误,所以,在悲观锁下,对数据的任何操作都会上锁
乐观锁乐观锁与悲观锁相反,乐观锁认为数据一般不会出问题,只是会访问的时候修改一下访问的数据,拿到最新的数据版本
使用watch可以当成redis的悲观锁用,被watch的资源,中间发生了修改,那么事务就提交失败。
如果watch 失败,那么就先unwatch解锁,然后再watch,只要再这其中没有修改,那么就事务就成功了
首先导入依赖
连接测试4.0.0 org.example Redis1.0-SNAPSHOT redis.clients jedis3.7.0 com.alibaba fastjson1.2.78 16 16
package zlx;
import redis.clients.jedis.Jedis;
public class RedisConnect
{
public static void main(String[] args) {
Jedis jedis =new Jedis("127.0.0.1",6379);
jedis.set("zlx", String.valueOf(0));
System.out.println(jedis.get("zlx"));
}
}
事务
package zlx;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
//测试redis 事务
public class RedisTransaction {
public static void main(String[] args) {
Jedis jedis =new Jedis("127.0.0.1",6379);
JSonObject jsons =new JSonObject();
jsons.put("hello","world");
jsons.put("name","zlx");
String result =jsons.toJSonString();
//开启事务
Transaction transaction =jedis.multi();
transaction.set("zlx1",result);
transaction.set("zlx2",result);
transaction.exec();
jedis.close();
}
}
SpringBoot集成redis
依赖
启动类与Controller4.0.0 org.springframework.boot spring-boot-starter-parent2.3.12.RELEASE org.example springboot-redis-demo1.0-SNAPSHOT org.springframework.boot spring-boot-starter-data-redisorg.springframework.boot spring-boot-starter-webcom.alibaba fastjson1.2.75 com.fasterxml.jackson.core jackson-databindorg.springframework.boot spring-boot-maven-plugin
package com.zfx.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RedisApp {
public static void main(String[] args) {
SpringApplication.run(RedisApp.class,args);
}
}
package com.zfx.redis.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RedisController {
@Autowired
RedisTemplate redisTemplate;
@GetMapping("/test/{key}/{value}")
public String test(@PathVariable String key ,@PathVariable String value) {
redisTemplate.opsForValue().set(key,value);
return redisTemplate.opsForValue().get(key).toString();
}
}



