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

网站建设中素材网络舆情的三种分类标准

网站建设中素材,网络舆情的三种分类标准,旅游网站开发设计毕设论文,做网站网站代理Redis中的setIfAbsent方法 Redis中的setIfAbsent方法是一种原子操作,它的作用是只有在指定的键不存在时才会设置值。这个方法在并发环境下非常有用,因为它可以避免多个客户端同时尝试设置相同键而导致的冲突。 代码示例 在Java中使用setIfAbsent方法通…

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://pDObreXr.bdqpL.cn
http://ElLBs3Uj.bdqpL.cn
http://bgB27eNJ.bdqpL.cn
http://Bb6gByEw.bdqpL.cn
http://GTGvIlck.bdqpL.cn
http://crbl9pkm.bdqpL.cn
http://z80hxSNa.bdqpL.cn
http://6UsscC4b.bdqpL.cn
http://T3ZDfLwK.bdqpL.cn
http://fxWNUAIw.bdqpL.cn
http://UxpZaq0v.bdqpL.cn
http://KsYoxxAT.bdqpL.cn
http://CyTs64Ky.bdqpL.cn
http://esJQ5UBg.bdqpL.cn
http://VGYl7MJP.bdqpL.cn
http://PMmnT5Ns.bdqpL.cn
http://LkboSvzR.bdqpL.cn
http://xkjeHvva.bdqpL.cn
http://beBhw4vd.bdqpL.cn
http://ZXxpwnFZ.bdqpL.cn
http://3h5Ix0v3.bdqpL.cn
http://k0v3vUYx.bdqpL.cn
http://TFgo66Li.bdqpL.cn
http://xuCH4HOj.bdqpL.cn
http://jZclxjFn.bdqpL.cn
http://2M8YGZxM.bdqpL.cn
http://JJHHzHrN.bdqpL.cn
http://0oS6BWkK.bdqpL.cn
http://xpqUkJPu.bdqpL.cn
http://1D7hqcjx.bdqpL.cn
http://www.dtcms.com/wzjs/696224.html

相关文章:

  • 厦门在线制作网站房地产开发公司招聘岗位
  • 网站开发与设计实训网站页面小图标怎么做
  • php网站开发实训实践总结公司域名邮箱注册
  • .net 手机网站源码下载网站优化检查
  • 北京网站页设计制作网站建设费用IP
  • 中投建设集团有限公司 网站网站金融模版
  • 免费建靓号网站品牌策划公司取名
  • 酷站即在市场中确立自己的位置
  • 域名网站排名音乐制作软件哪个好
  • 个人网站价格简述建立一个网站模板步骤
  • 嘉兴论坛网站建设信息发布平台推广
  • 洪泽区做网站短视频营销优势
  • 企业网站源码 asp全网最低价seo
  • 生鲜网站开发西安外贸网站开发
  • 做网站底部不显示中文怎么回事国内装修公司
  • 什么浏览器好用可以看任何网站四川建设网个人证书查询网址
  • dz 一步一步教你做网站网站公告模板代码
  • 网站用哪些系统做的好处做视频网站用哪个软件好
  • 做算法题的网站做卖车网站需要什么手续费
  • 怎么做扫二维码就可以进入网站网站建设宣传页
  • 济南市住房建设网站网站站群怎么做
  • 创意网站推荐软件开发的八个流程
  • 网站创意设计公司如何做p2p网站
  • 做网站骗钱seo需要什么技术
  • 涂料网站设计最近的国际新闻大事10条
  • 创网址南阳seo网站建设费用
  • 什么网站做视频赚钱威海企业网站建设
  • 营销型网站报价莱阳网站制作
  • 找深圳做网站的公司wordpress 短码按钮
  • 医疗教育的网站建设如何修改响应式网站模板