声明Bean
实现缓存异步提交方法
/**
* 手动刷新请求
*
* @return
* @throws IOException
*/
@Bean("redisAsyncCommands")
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public RedisAsyncCommands<String, String> getRedisAsyncCommands() throws IOException {
final FileInputStream fileInputStream = new FileInputStream(Path.getCurrentPath(CommonConfig.class) + "/config/redisms.properties");
Properties pro = new Properties();
pro.load(fileInputStream);
final String host = pro.getProperty("host");
final String port = pro.getProperty("port");
final String password = pro.getProperty("password");
final String timeout = pro.getProperty("timeout");
log.info("host={}, port={}, timeout={}", host, port, timeout);
final RedisURI uri = RedisURI.Builder.redis(host, Integer.parseInt(port)).withPassword(password).withTimeout(Duration.ofMillis(Long.parseLong(timeout))).build();
NettyCustomizer nettyCustomizer = new NettyCustomizer() {
@Override
public void afterChannelInitialized(Channel channel) {
channel.pipeline().addLast(
new IdleStateHandler(0, 0, 10));
channel.pipeline().addLast(new ChannelDuplexHandler() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent evnet = (IdleStateEvent) evt;
if (evnet.state().equals(IdleState.ALL_IDLE)) {
log.info("LETTUCE CLOSE CHANNEL {} ", ctx.channel());
ctx.channel().close();
}
}
ctx.fireUserEventTriggered(evt);
}
});
}
};
ClientResources resources = ClientResources.builder().nettyCustomizer(nettyCustomizer).build();
final io.lettuce.core.RedisClient redisClient = io.lettuce.core.RedisClient.create(resources, uri);
LettuceWrapper.of("business6841_async", redisClient);
final StatefulRedisConnection<String, String> connect = redisClient.connect();
connect.setAutoFlushCommands(false);
return connect.async();
}
引用资源
/**
* RedisAsyncCommands
*/
@Resource
private RedisAsyncCommands<String, String> redisAsyncCommands;
创建添加到异步的方法
public RedisFuture<Map<String, String>> hgetAllAsync(String key) {
return redisAsyncCommands.hgetall(key);
}
创建从异步获取方法
public List<Map<String, String>> flushCommands(List<RedisFuture<Map<String, String>>> redisFutures) {
// 刷新提交
redisAsyncCommands.flushCommands();
return redisFutures.stream().map(redisFuture -> {
try {
return redisFuture.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return null;
}).collect(Collectors.toList());
}