当前位置: 首页 > news >正文

Redis中的setIfAbsent方法和execute

Redis中的setIfAbsent方法

Redis中的setIfAbsent方法是一种原子操作,它的作用是只有在指定的键不存在时才会设置值。这个方法在并发环境下非常有用,因为它可以避免多个客户端同时尝试设置相同键而导致的冲突。

代码示例

在Java中使用setIfAbsent方法通常结合RedisTemplate来实现,语法如下:

redisTemplate.opsForValue().setIfAbsent(key, value, timeout, unit);

其中,key是要设置的键,value是要设置的值,timeoutunit是可选参数,分别表示键的过期时间和时间单位。

操作解释

setIfAbsent方法首先会检查给定的键是否存在。如果键不存在,它将创建一个新的键并设置给定的值。如果键已经存在,它将不执行任何操作。这个过程是原子的,意味着在检查和设置键的过程中不会有其他客户端或线程干扰。

应用场景

  • 分布式锁:可以用来实现分布式锁,确保某个操作在短时间内只能由一个节点执行。

  • 缓存:在缓存系统中,用于保证某个缓存项只有在不存在时才会被创建和存储。

  • 分布式事件处理:保证某个事件只被处理一次。

注意事项

使用setIfAbsent时需要注意并发问题,虽然是原子操作,但在高并发环境下仍可能存在竞态条件。合理设置键的过期时间可以提高系统的灵活性和性能。此外,在使用时需要注意异常处理,例如,当键已经存在时,该方法不会抛出异常,而是返回false0表示操作未成功。

在实际应用中,setIfAbsent方法可以有效地解决并发环境下的数据一致性问题,是实现分布式锁和缓存等功能的关键工具。

Redis RedisTemplate 核心方法 execute 详解

在 RedisTemplate 中,定义了几个 execute() 方法,这些方法是 RedisTemplate 的核心方法。RedisTemplate 中很多其他方法均是通过调用 execute 来执行具体的操作。例如:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

/*

 * (non-Javadoc)

 * @see org.springframework.data.redis.core.RedisOperations#delete(java.util.Collection)

 */

@Override

public Long delete(Collection<K> keys) {

   if (CollectionUtils.isEmpty(keys)) {

      return 0L;

   }

   byte[][] rawKeys = rawKeys(keys);

   return execute(connection -> connection.del(rawKeys), true);

}

上述方法是 RedisTemplate 中 delete 方法的源码,它就是使用 execute() 来执行具体的删除操作(即调用 connection.del(rawKeys) 方法)。

方法说明如下表:

方法定义方法说明
<T> T  execute(RedisCallback<T> action)在 Redis 连接中执行给定的操作
<T> T  execute(RedisCallback<T> action, boolean exposeConnection)在连接中执行给定的操作对象,可以公开也可以不公开。
<T> T  execute(RedisCallback<T> action, boolean exposeConnection, boolean pipeline)在可以公开或不公开的连接中执行给定的操作对象。
<T> T  execute(RedisScript<T> script, List<K> keys, Object... args)执行给定的 RedisScript
<T> T  execute(RedisScript<T> script, RedisSerializer<?> argsSerializer, RedisSerializer<T> resultSerializer, List<K> keys, Object... args)执行给定的 RedisScript,使用提供的 RedisSerializers 序列化脚本参数和结果。
<T> T  execute(SessionCallback<T> session)执行 Redis 会话

示例

execute(RedisCallback) 简单用法

使用 RedisTemplate 直接调用 opsFor** 来操作 Redis 数据库,每执行一条命令是要重新拿一个连接,因此很耗资源。如果让一个连接直接执行多条语句的方法就是使用 RedisCallback(它太复杂,不常用),推荐使用 SessionCallback。

本例将演示使用 RedisCallback 向 Redis 写入数据,然后再将写入的数据取出来,输出到控制台。如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

package com.hxstrive.redis.redistemplate.execute;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.dao.DataAccessException;

import org.springframework.data.redis.connection.RedisConnection;

import org.springframework.data.redis.connection.RedisStringCommands;

import org.springframework.data.redis.core.RedisCallback;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)

@SpringBootTest

public class ExecuteSimple {

    /** 注入 RedisTemplate */

    @Autowired

    private RedisTemplate<String,String> redisTemplate;

    @Test

    public void contextLoads() {

        redisTemplate.execute(new RedisCallback<String>() {

            @Override

            public String doInRedis(RedisConnection connection) throws DataAccessException {

                RedisStringCommands commands = connection.stringCommands();

                // 写入缓存

                commands.set("execute_key".getBytes(), "hello world".getBytes());

                // 从缓存获取值

                byte[] value = commands.get("execute_key".getBytes());

                System.out.println(new String(value));

                return null;

            }

        });

    }

}

运行示例,输出结果如下:

1

hello world

其实,在 RedisTemplate 中,其他很多方法均是通过调用 execute() 方法来实现,只是不同的方法实现不同的回调接口。部分源码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

// ...

@Override

public Long increment(K key) {

   byte[] rawKey = rawKey(key);

   return execute(connection -> connection.incr(rawKey), true);

}

/*

 * (non-Javadoc)

 * @see org.springframework.data.redis.core.ValueOperations#increment(java.lang.Object, long)

 */

@Override

public Long increment(K key, long delta) {

   byte[] rawKey = rawKey(key);

   return execute(connection -> connection.incrBy(rawKey, delta), true);

}

@Override

public void set(K key, V value, long timeout, TimeUnit unit) {

   byte[] rawKey = rawKey(key);

   byte[] rawValue = rawValue(value);

   execute(new RedisCallback<Object>() {

      @Override

      public Object doInRedis(RedisConnection connection) throws DataAccessException {

         potentiallyUsePsetEx(connection);

         return null;

      }

      public void potentiallyUsePsetEx(RedisConnection connection) {

         if (!TimeUnit.MILLISECONDS.equals(unit) || !failsafeInvokePsetEx(connection)) {

            connection.setEx(rawKey, TimeoutUtils.toSeconds(timeout, unit), rawValue);

         }

      }

      private boolean failsafeInvokePsetEx(RedisConnection connection) {

         boolean failed = false;

         try {

            connection.pSetEx(rawKey, timeout, rawValue);

         catch (UnsupportedOperationException e) {

            // in case the connection does not support pSetEx return false to allow fallback to other operation.

            failed = true;

         }

         return !failed;

      }

   }, true);

}

// ...

execute(SessionCallback) 简单用法

使用 RedisTemplate 直接调用 opsFor** 来操作 Redis 数据库,每执行一条命令是要重新拿一个连接,因此很耗资源。如果让一个连接直接执行多条语句的方法就是使用 SessionCallback,还可以使用 RedisCallback(它太复杂,不常用)。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

package com.hxstrive.redis.redistemplate.execute;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.dao.DataAccessException;

import org.springframework.data.redis.core.RedisOperations;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.core.SessionCallback;

import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)

@SpringBootTest

public class SessionCallbackSimple {

    /** 注入 RedisTemplate */

    @Autowired

    private RedisTemplate<String,String> redisTemplate;

    @Test

    public void contextLoads() {

        redisTemplate.execute(new SessionCallback() {

            @Override

            public String execute(RedisOperations operations) throws DataAccessException {

                operations.opsForValue().set("valueK1""value1");

                System.out.println("valueK1 = " + operations.opsForValue().get("valueK1"));

                operations.opsForList().leftPushAll("listK1""one""two");

                System.out.println("listK1 = " + operations.opsForList().size("listK1"));

                return null;

            }

        });

    }

}

运行示例,输出如下:

1

2

valueK1 = value1

listK1 = 2

execute(RedisScript) 简单用法

该示例使用 Lua 脚本实现获取锁的功能,代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

package com.hxstrive.redis.redistemplate.execute;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.core.script.DefaultRedisScript;

import org.springframework.test.context.junit4.SpringRunner;

import java.util.Collections;

@RunWith(SpringRunner.class)

@SpringBootTest

public class RedisScriptSimple {

    /** 注入 RedisTemplate */

    @Autowired

    private RedisTemplate<String,String> redisTemplate;

    @Test

    public void contextLoads() {

        // 使用 lua 脚本实现获取锁

        // ARGV[1] = lock-key

        // ARGV[2] = 30

        String script = "local key = ARGV[1];" +

                "local expiration = ARGV[2];" +

                "local value = 1;" +

                "if redis.call('EXISTS', key) == 1 then " +

                "  return -1 " // 如果键存在,则返回-1

                "else " +

                "  redis.call('SET', key, value);" // 如果键不存在,则设置键和值

                "  redis.call('EXPIRE', key, expiration);" // 为键设置过期时间

                "  return 1;" // 返回1,表示锁获取成功

                "end";

        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);

        // 其中,lock-key 表示锁的键,30 表示过期时间为30秒

        Long val = redisTemplate.execute(redisScript, Collections.EMPTY_LIST, "lock-key""30");

        System.out.println("val = " + val);

        // 如果锁获取成功,则进入下一步操作

        if(null != val && val == 1) {

            System.out.println("获取锁成功");

        else {

            System.err.println("获取锁失败");

        }

    }

}

运行示例,输出如下:

1

2

val = 1

获取锁成功

http://www.lqws.cn/news/129547.html

相关文章:

  • 使用cursor 编辑器开发 Vue项目,配置ESlint自动修复脚本,解决代码不规范引起的报错无法运行项目问题
  • Flutter如何支持原生View
  • node 进程管理工具 pm2 的详细说明 —— 一步一步配置 Ubuntu Server 的 NodeJS 服务器详细实录 7
  • excel从不同的excel表匹配数据
  • 采用 Docker GPU 部署的 Ubuntu 或者 windows 桌面环境
  • centos 9/ubuntu 一次性的定时关机
  • Python训练第四十四天
  • 【EasyExcel】导出时添加页眉页脚
  • 【Oracle】存储过程
  • Oracle实用参考(13)——Oracle for Linux静默安装(1)
  • Delphi中实现批量插入数据
  • oracle从表B更新拼接字段到表A
  • Sql Server 中常用语句
  • 鸿蒙Navigation路由导航-基本使用介绍
  • 【RAG召回优化】rag召回阶段方法探讨
  • 服务器--宝塔命令
  • 【和春笋一起学C++】(十七)C++函数新特性——内联函数和引用变量
  • 边缘计算网关赋能沸石转轮运行故障智能诊断的配置实例
  • Webpack常见的插件和模式
  • Rocket客户端消息确认机制
  • 电路图识图基础知识-降压启动(十五)
  • 2. 库的操作
  • RabbitMQ 的异步化、解耦和流量削峰三大核心机制
  • hadoop集群单词统计(ssh与web)
  • GPUCUDA 发展编年史:从 3D 渲染到 AI 大模型时代(上)
  • 涂胶协作机器人解决方案 | Kinova Link 6 Cobot在涂胶工业的方案应用与价值
  • 线性模型选择中容易被忽视的关键洞察
  • 树莓派系列教程第九弹:Cpolar内网穿透搭建NAS
  • Linux 下支持 **截图 + 录屏** 的高级工具对比
  • c#开发AI模型对话