论坛首页 Java企业应用论坛

备忘使用spring-data-redis中的redistemplate的一个大坑

浏览 22914 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-07-16  
在项目开发过程中,想要进行redis的并发控制,这时候,想当然地使用了spring-data-redis库中template里面提供的multi()和exec()方法,但是蛋疼地发现,使用了之后,就出现了如下异常:

org.springframework.dao.InvalidDataAccessApiUsageException: ERR EXEC without MULTI; nested exception is redis.clients.jedis.exceptions.JedisDataException: ERR EXEC without MULTI


在google搜了一下,才知道,原来是目前该库的redistemplate的multi和exec方法,都是新产生连接,而非使用本来的连接,这个异常,也是由于这个原因所以才导致的。(因为新连接中,直接执行退出同步,系统肯定会去找是从哪儿开始同步的,这一找,发现没有开始同步的命令,就会抛出异常了)

这个时候,只能自己调用底层的RedisCallBack和Jedis去实现底层redis语句了。
类似这样:

		Jedis jedis = new Jedis("localhost",6379);
		new RedisCallback<Object>() {
			public Object doInRedis(RedisConnection connection) throws DataAccessException {
				connection.multi();
				return null;
			}
		}.doInRedis(new JedisConnection(jedis));



这时候肯定会有个疑问,既然这个template每次都会生成新连接,那这个multi和exec命令还有个蛋用??

官方是这么回答的:
The methods are exposed in case the connection is shared across methods. Currently we don't provide any out of the box support for connection binding but the RedisTemplate supports it - just like with the rest of the templates, one connection could be bound to the running thread and the RT will use it without creating new ones.

大致意思是这些方法目前是没有用的。等到以后template可以支持绑定connection到其他运行中的连接时,这俩方法就有用了。

参考资料
http://forum.springsource.org/showthread.php?113738-spring-data-redis-transactions
   发表时间:2012-07-17   最后修改:2012-07-17

针对这个问题分析了spring-data-redis的源码

在源码中找到的解决方案

详情见博文  http://jimgreat.iteye.com/blog/1596058

 

0 请登录后投票
   发表时间:2012-10-17  
redis//watch,multi,exec

http://stackoverflow.com/questions/10750626/transactions-and-watch-statement-in-redis
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics