Java多线程连redis_Spring Redis模板与Jedis连接工厂,Redis独立配置和多线程

我在多线程环境中使用Spring Redis模板 . 一个线程将数据保存到Redis中,另一个线程(调度程序)从中获取数据 . JedisConnectionFactory用于redis模板 . 以下是用于获取redis连接的代码段:

JedisConnectionFactory jedisConnectionFactory() {

JedisConnectionFactory jedisConnectionFactory = null;

try {

RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(hostName,

port);

jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration);

} catch (RedisConnectionFailureException e) {

LOGGER.error("Connection break with redis " + e.getMessage());

}

return jedisConnectionFactory;

}

/**

* Redis template.

*

* @return the redis template

*/

@Bean

public RedisTemplate redisTemplate() {

final RedisTemplate template = new RedisTemplate();

template.setConnectionFactory(jedisConnectionFactory());

template.setValueSerializer(new GenericToStringSerializer(Object.class));

template.setEnableTransactionSupport(true);

return template;

}

使用构造函数自动连接获取redis模板的实例,如下所示:

@Autowired

public A(RedisTemplate redisTemplate) {

this.redisTemplate = redisTemplate;

}

我使用redis模板的“findAll()”方法从Redis获取数据时遇到异常:

org.springframework.data.redis.RedisConnectionFailureException:java.net.SocketException:peer by peer:socket write error;嵌套异常是redis.clients.jedis.exceptions.JedisConnectionException:java.net.SocketException:通过对等方重置连接:套接字写入错误

以下是我的发现:

当TCP套接字要"closing"并且您的代码尚未得到通知时,会发生

连接由对等异常重置 . (对于已关闭的连接,尚未通知findAll的线程) .

Redis模板是线程安全的(仅在使用连接池时)并且自己处理连接管理 . 可能会发生这样的情况:当线程将数据保存到redis并关闭连接时,仅在此期间,发生了获取操作并要求数据 . 在这种情况下,服务器可能已发出RST命令,但获取操作可能尚未获取它 .

可以使用Jedis池配置;但是有一些折旧的方法可以在以后导致升级问题 .

请建议使用“JedisConnectionFactory”,“RedisStandAloneConfiguration”和“RedisTemplate”处理多线程的最佳方法 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值