是以太山不让土壤,故能成其大;河海不择细流,故能就其深。——李斯
多用于排行榜、统计访问量、签到天数等场景
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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| package com.ruben;
import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.DependsOn; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.support.atomic.RedisAtomicLong; import org.springframework.test.annotation.Rollback;
import javax.annotation.Resource; import java.math.BigDecimal; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Optional; import java.util.concurrent.TimeUnit;
@SpringBootTest @Rollback(false) public class RedisDemo {
@Resource private StringRedisTemplate stringRedisTemplate;
@Test public void redisIncrementDemo() { RedisAtomicLong redisAtomicLong = Optional.ofNullable(stringRedisTemplate.getConnectionFactory()).map(factory -> new RedisAtomicLong("ruben", factory)).orElseThrow(() -> new RuntimeException("redis获取连接失败")); long longValue = redisAtomicLong.incrementAndGet(); System.out.println("自增并获取" + longValue); longValue = redisAtomicLong.getAndIncrement(); System.out.println("获取并自增" + longValue); longValue = redisAtomicLong.addAndGet(2L); System.out.println("相加并获取" + longValue); longValue = redisAtomicLong.updateAndGet(i -> i + 2); System.out.println("修改并获取" + longValue); longValue = redisAtomicLong.decrementAndGet(); System.out.println("自减并获取" + longValue); longValue = redisAtomicLong.accumulateAndGet(6L, Long::max); System.out.println("计算和5的最大值并获取" + longValue); longValue = redisAtomicLong.accumulateAndGet(5L, (left, right) -> new BigDecimal(left).multiply(new BigDecimal(right)).longValue()); System.out.println("计算两数相乘并获取" + longValue); redisAtomicLong.set(0L); longValue = redisAtomicLong.get(); System.out.println("获取" + longValue); redisAtomicLong.expire(30, TimeUnit.SECONDS); redisAtomicLong.expire(Duration.of(30, ChronoUnit.SECONDS)); Long expire = redisAtomicLong.getExpire(); System.out.println("获取过期时间" + expire); }
}
|
写的应该是比较全了,常用的都放这里了