知方号

知方号

redis incr 原子操作(结合增加1并返回增加之后的值:add+1&get)

git地址 INCR key 可用版本: >= 1.0.0 时间复杂度: O(1) 为键 key 储存的数字值加上一。

如果键 key 不存在, 那么它的值会先被初始化为 0 , 然后再执行 INCR 命令。

如果键 key 储存的值不能被解释为数字, 那么 INCR 命令将返回一个错误。

本操作的值限制在 64 位(bit)有符号数字表示之内。

Note

INCR 命令是一个针对字符串的操作。 因为 Redis 并没有专用的整数类型, 所以键 key 储存的值在执行 INCR 命令时会被解释为十进制 64 位有符号整数。

返回值 INCR 命令会返回键 key 在执行加一操作之后的值。

代码示例 redis> SET page_view 20 OK

redis> INCR page_view (integer) 21

redis> GET page_view # 数字值在 Redis 中以字符串的形式保存 “21”

org.springframework.bootspring-boot-starter-data-redis spring: redis:# database: 0 host: 127.0.0.1 password: xfxMaster973339_2018 port: 6739 timeout: 3000 # 连接超时时间 单位 ms(毫秒)# cluster:# nodes: 10.3.1.4:7000,10.3.1.4:7001,...,10.3.1.4:7008# pool:# max-idle: 8 # 连接池中的最大空闲连接,默认值也是8# min-idle: 0 # 连接池中的最小空闲连接,默认值也是0# max-active: 8 # 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。# max-wait: -1 # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出 package redisIncrTest.redisIncr;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.support.atomic.RedisAtomicLong;/** * redisTemplate测试 incr原子自增操作 * */@SpringBootApplicationpublic class App implements CommandLineRunner{@SuppressWarnings("rawtypes")@Autowired private RedisTemplate redisTemplate;//redis的键-keyprivate final static String KEY = "HSJ-QPS-INCR";//线程池5个线程private static ExecutorService fixedPool3 = Executors.newFixedThreadPool(8);public static void main(String[] args) {SpringApplication.run(App.class, args);}@Overridepublic void run(String... args) throws Exception {RedisAtomicLong redisAtomicLong = new RedisAtomicLong(KEY, redisTemplate.getConnectionFactory());//10个线程都去让他增加,总共1000002次for(long i = 0;i < 1000002;i++){fixedPool3.execute(()->{redisAtomicLong.getAndIncrement();});}}}

后记:秒杀系统实现的一种思路,使用redisson分布式锁+原子incr/decr挡住QPS,秒杀成功的insert入库。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lizi9903@foxmail.com举报,一经查实,本站将立刻删除。