synchronous redis transaction

Mark: http://jimgreat.iteye.com/blog/1596058


One method

For spring-data-redis, should use "redisTemplate.execute(new SessionCallback<Object>{..}); " for synchronous redis transaction(watch, multi, exec).

            // make sure atomic operation for taskKey in Redis
            // if retry count is larger than 5 times, abandon it.
            redisTemplate.execute(new SessionCallback<Integer>() {
                @Override
                public Integer execute(RedisOperations operations) throws DataAccessException {
                    int retries = 5;
                    do {
                        // redis watch
                        operations.watch(taskKey);
                        Vo vo = handle.getTaskData(taskKey, Vo.class);
                        boolean needUpdate = checkForUpdate(vo, taskKey, event);
                        if (!needUpdate) {
                            log.warn("Save: [{}] is abandoned for taskKey: {}, since checkForUpdate false.",
                                    notification, taskKey);
                            break;
                        }

                        // begin transaction
                        operations.multi();
                        if (event.isComplete()) {
                            vo.setStatus(Status.READY);
                            vo.complete();
                        }
                        vo.setSequenceNumber(sequenceNumber);
                        handle.updateTaskData(taskKey, vo);

                        // commit transaction
                        List<Object> result = operations.exec();
                        if (result != null) {
                            log.info("Save: [{}] is saved to taskKey: {}.", notification, taskKey);
                            break;
                        }
                        else if (retries == 1) {
                            log.warn("Save: [{}] is abandoned for taskKey: {}, since over retries: {}.", notification,
                                    taskKey, retries);
                        }
                        retries--;
                        log.info("Save taskKey: {}, retry: {}.", taskKey, retries);
                    } while (retries > 0);
                    return retries;
                }
            });

The other method

Use lua RedisScript (org.springframework.data.redis.core.script.DefaultRedisScript), lua .

        examplehttp://www.cnblogs.com/yanghuahui/p/3697996.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值