在redission 2.9.0版本之前是有BUG,在实现下面代码时,第一次是成功的,但是在第二次就会失败:
RedissonClient client;//client参考别的demo
RMapCache<String, Integer> mapCache = client.getMapCache("nameSpace");
mapCache.putIfAbsent("redisKey", 0, 1, TimeUnit.DAYS);//当不存在redisKey时,就放置这个redis,存在则不放置
在redission 2.9.0(3.4.1)版本之后修复BUG,多次操作是成功的:
RedissonClient client = RedissonHolder.getClient();//具体实现参考别的demo
RMapCache<String, Integer> mapCache = client.getMapCache("nameSpace",IntegerCodec.INSTANCE);
String redisKey = channel + "-" + userId;
mapCache.putIfAbsent("redisKey", 0, 1, TimeUnit.DAYS);
logger.info("获取redis计数器:{}", redisKey);
int incr = mapCache.addAndGet(redisKey, 1);//加1并获取计算后的值
参考pom:
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.4.1</version>
</dependency>
可参考redis demo:
import java.io.IOException;
import java.io.InputStream;
import java.util.ResourceBundle; import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class RedissonHolder { private static final Logger LOGGER = LoggerFactory.getLogger(RedissonHolder.class); private static final RedissonHolder HOLDER = new RedissonHolder(); private RedissonClient redisson; private RedissonHolder() { String location = ResourceBundle.getBundle("redisson").getString("redisson.json.location");
InputStream inputStream = RedissonHolder.class.getClassLoader().getResourceAsStream(location);
Config config = null;
try {
config = Config.fromJSON(inputStream);
} catch (IOException e) {
LOGGER.error("获取Redisson配置文件失败", e);
}
this.redisson = Redisson.create(config);
} public static RedissonClient getClient() {
return HOLDER.redisson;
} }
redisson.properties(等号后面全部换成一行) :
redisson.json.location ={"singleServerConfig":{"idleConnectionTimeout":10000,
"pingTimeout":1000,
"connectTimeout":10000,
"timeout":5000,
"retryAttempts":5,
"retryInterval":1500,
"reconnectionTimeout":3000,
"failedAttempts":3,
"password":"root",
"subscriptionsPerConnection":5,
"clientName":null,
"address":"redis://my.redis.com:6379",
"subscriptionConnectionMinimumIdleSize":1,
"subscriptionConnectionPoolSize":50,
"connectionMinimumIdleSize":10,
"connectionPoolSize":64,
"database":0,
"dnsMonitoring":false,
"dnsMonitoringInterval":5000
},
"threads":0,
"nettyThreads":0,
"codec":null,
"useLinuxNativeEpoll":false
}
基于 springboot 的 redisTemplate计数器
redisTemplate基本配置参考 http://www.cnblogs.com/tietazhan/p/7479585.html
然后就可以直接使用内部函数
redisTemplate.opsForHash().increment(H var1, HK var2, long var3);
第一个为缓存key值,第二个为hashKey值,第三个为增量值。