Example usage for org.springframework.data.redis.core RedisOperations multi

List of usage examples for org.springframework.data.redis.core RedisOperations multi

Introduction

In this page you can find the example usage for org.springframework.data.redis.core RedisOperations multi.

Prototype

void multi();

Source Link

Document

Mark the start of a transaction block.

Usage

From source file:com.greenline.guahao.biz.manager.cache.hrs.DictCacheManager.java

/**
 * //w ww  .j a v a 2  s  . com
 * 
 * @param list
 */
public void setDicts(String dictId, final List<DictDO> list) {

    if (StringUtils.isEmpty(dictId) || list == null || list.isEmpty()) {
        return;
    }

    final RedisList<String> redislist = dictList(dictId);
    redislist.clear();
    redislist.getOperations().execute(new SessionCallback<Object>() {
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public Object execute(RedisOperations operations) throws DataAccessException {
            operations.watch(redislist.getKey());
            operations.multi();
            for (DictDO obj : list) {
                redislist.add(jackjson.writeString(obj));
            }
            operations.exec();
            return null;
        }
    });

    setExpire(redislist);
}

From source file:org.shareok.data.redis.UserDaoImpl.java

@Override
public void deleteUserByUserId(final long userId) {
    try {//  w w  w.  j av a 2s.com
        redisTemplate.setConnectionFactory(connectionFactory);
        final String key = RedisUtil.getUserQueryKey(userId);
        Map userInfo = redisTemplate.opsForHash().entries(key);
        final String email = (String) userInfo.get("email");
        List<Object> results = redisTemplate.execute(new SessionCallback<List<Object>>() {
            @Override
            public List<Object> execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                operations.opsForHash().delete(ShareokdataManager.getRedisUserNameIdMatchingTable(), email);
                operations.opsForHash().getOperations().delete(key);

                List<Object> opList = operations.exec();
                if (!opList.get(0).equals(true) && !opList.get(0).equals(Long.valueOf(1))) {
                    operations.discard();
                }
                return opList;
            }
        });
    } catch (Exception ex) {
        logger.error("Cannot delete a user with ID " + userId, ex);
    }
}

From source file:org.shareok.data.redis.UserDaoImpl.java

@Override
@Transactional/*from  w ww . ja  va  2  s . c o  m*/
public RedisUser addUser(final RedisUser user) {
    try {
        redisTemplate.setConnectionFactory(connectionFactory);
        RedisUser existedUser = findUserByUserEmail(user.getEmail());
        if (null != existedUser) {
            return existedUser;
        }

        RedisAtomicLong userIdIndex = new RedisAtomicLong(ShareokdataManager.getRedisGlobalUidSchema(),
                redisTemplate.getConnectionFactory());
        long uidCount = userIdIndex.incrementAndGet();
        final String uid = String.valueOf(uidCount);

        List<Object> results = redisTemplate.execute(new SessionCallback<List<Object>>() {
            @Override
            public List<Object> execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                operations.boundHashOps("user:" + uid);
                operations.opsForHash().put("user:" + uid, "userName",
                        (null != user.getUserName() ? user.getUserName() : user.getEmail()));
                operations.opsForHash().put("user:" + uid, "email", user.getEmail());
                operations.opsForHash().put("user:" + uid, "userId", uid);
                operations.opsForHash().put("user:" + uid, "password", user.getPassword());
                operations.opsForHash().put("user:" + uid, "isActive", String.valueOf(true));
                operations.opsForHash().put("user:" + uid, "sessionKey",
                        (null != user.getSessionKey() ? user.getSessionKey() : ""));
                operations.opsForHash().put("user:" + uid, "startTime",
                        (null != user.getStartTime()
                                ? ShareokdataManager.getSimpleDateFormat().format(user.getStartTime())
                                : (ShareokdataManager.getSimpleDateFormat().format(new Date()))));

                operations.boundHashOps("users");
                operations.opsForHash().put("users", user.getEmail(), uid);

                List<Object> userList = operations.exec();
                if (!userList.get(0).equals(true)) {
                    operations.discard();
                }
                return userList;
            }
        });
    } catch (Exception ex) {
        logger.error("Cannot add new user", ex);
    }
    return user;
}

From source file:com.greenline.guahao.biz.manager.cache.hrs.ShiftCaseCacheManager.java

/**
 * ?/*from   w w w. j a va  2s.c om*/
 * 
 * @param list
 */
public void setShiftCases(ShiftQuery query, final List<ShiftCaseDO> list) {
    if (query == null) {
        return;
    }

    if (list == null || list.isEmpty()) {
        String key = getIsCachedKey(queryKey(query));
        // 
        String isCached = template.opsForValue().get(key);
        if (StringUtils.isEmpty(isCached)) {
            setExpire(key, "true");
        }
        return;
    }
    // add to list
    final RedisList<String> redislist = shiftQueryList(query);
    redislist.clear();
    redislist.getOperations().execute(new SessionCallback<Object>() {
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public Object execute(RedisOperations operations) throws DataAccessException {
            operations.watch(redislist.getKey());
            operations.multi();
            for (ShiftCaseDO obj : list) {
                redislist.add(jackjson.writeString(obj));
            }
            operations.exec();
            return null;
        }
    });
    // 
    boolean expire = redislist.expire(this.getExpireTime(), TimeUnit.SECONDS);
    if (!expire) {
        // ??key
        template.delete(queryKey(query));
    }
}

From source file:com.greenline.guahao.biz.manager.cache.hrs.HospitalCacheManager.java

/**
 * /*  w w w . j a v  a2  s.com*/
 * 
 * @param list
 */
public void setHospLevels(final List<HospitalLevelDO> list) {
    if (list == null || list.isEmpty()) {
        return;
    }

    final RedisList<String> leveList = hospitallevels();
    leveList.clear();
    leveList.getOperations().execute(new SessionCallback<Object>() {
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public Object execute(RedisOperations operations) throws DataAccessException {
            operations.watch(leveList.getKey());
            operations.multi();
            for (HospitalLevelDO obj : list) {
                leveList.add(jackjson.writeString(obj));
            }
            operations.exec();
            return null;
        }
    });
    // 
    setExpire(leveList);
}

From source file:com.greenline.guahao.biz.manager.cache.hrs.HospitalCacheManager.java

/**
 * ?/*from w  w w. j av a 2 s . c om*/
 * 
 * @param hospitalId
 * @param list
 */
public void setClinicTypes(String hospitalId, final List<ClinicTypeDO> list) {
    if (StringUtils.isEmpty(hospitalId) || list == null || list.isEmpty()) {
        return;
    }
    final RedisList<String> clinicTypes = clinicTypes(hospitalId);
    clinicTypes.clear();
    clinicTypes.getOperations().execute(new SessionCallback<Object>() {
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public Object execute(RedisOperations operations) throws DataAccessException {
            operations.watch(clinicTypes.getKey());
            operations.multi();
            for (ClinicTypeDO obj : list) {
                clinicTypes.add(obj.getId());
            }
            operations.exec();
            return null;
        }
    });

    for (ClinicTypeDO obj : list) {
        setClinicType(obj.getId(), obj);
    }
    setExpire(clinicTypes);
}

From source file:com.company.project.service.dao.RedisDao.java

/**
 * 4.9. Redis Transactions - http://docs.spring.io/spring-data/redis/docs/current/reference/html/
 * Add value to set. Utilize Session Callback
 * @param key//from   w  w w .  j  av a  2  s  .  c  o m
 * @param value
 * @return 
 */
public long addUsingOpsForSetUsingSesssionCallback(final String key, final Object value) {
    //execute a transaction
    List<Object> txResults = redisTemplate.execute(new SessionCallback<List<Object>>() {
        @Override
        public List<Object> execute(RedisOperations operations) throws DataAccessException {
            operations.multi();
            operations.opsForSet().add(key, value);

            // This will contain the results of all ops in the transaction
            return operations.exec();
        }
    });

    if (txResults != null && !txResults.isEmpty()) {
        System.out.println("Number of items added to set: " + txResults.get(0));
        try {
            int itemsAdded = Integer.parseInt("" + txResults.get(0));
            return itemsAdded;
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
    }

    return 0;
}

From source file:org.shareok.data.redis.job.JobDaoImpl.java

@Override
@Transactional/*from   w  ww  .ja  va2 s  .c  om*/
public long startJob(long uid, int jobType, int repoType, int serverId, Date startTime) {

    long jobIdCount = -1;

    try {
        redisTemplate.setConnectionFactory(connectionFactory);

        RedisAtomicLong jobIdIndex = new RedisAtomicLong(ShareokdataManager.getRedisGlobalJobIdSchema(),
                redisTemplate.getConnectionFactory());

        jobIdCount = jobIdIndex.incrementAndGet();
        final String jobId = String.valueOf(jobIdCount);
        final String uidStr = String.valueOf(uid);
        final String jobTypeStr = String.valueOf(jobType);
        final String repoTypeStr = String.valueOf(repoType);
        final String serverIdStr = String.valueOf(serverId);
        final Date startTimeStr = startTime;

        List<Object> results = redisTemplate.execute(new SessionCallback<List<Object>>() {
            @Override
            public List<Object> execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                operations.boundHashOps("job:" + jobId);
                operations.opsForHash().put("job:" + jobId, "userId", uidStr);
                operations.opsForHash().put("job:" + jobId, "jobId", jobId);
                operations.opsForHash().put("job:" + jobId, "status", "4");
                operations.opsForHash().put("job:" + jobId, "type", jobTypeStr);
                operations.opsForHash().put("job:" + jobId, "repoType", repoTypeStr);
                operations.opsForHash().put("job:" + jobId, "startTime",
                        (null != startTimeStr ? ShareokdataManager.getSimpleDateFormat().format(startTimeStr)
                                : ShareokdataManager.getSimpleDateFormat().format(new Date())));
                operations.opsForHash().put("job:" + jobId, "endTime", "");
                operations.opsForHash().put("job:" + jobId, "serverId", serverIdStr);

                operations.boundSetOps("user_" + uidStr + "_job_set").add(jobId);

                List<Object> jobList = operations.exec();
                if (!jobList.get(0).equals(true)) {
                    operations.discard();
                }
                return jobList;
            }
        });
    } catch (Exception ex) {
        logger.error("Cannot start a new job.", ex);
    }
    return jobIdCount;
}

From source file:org.shareok.data.redis.job.JobDaoImpl.java

@Override
public RedisJob createJob(final long uid, final int jobType, final Map<String, String> values) {
    long jobIdCount = -1;
    final RedisJob newJob = new RedisJob();

    try {//from   ww w . j av  a  2 s  .  c o  m
        redisTemplate.setConnectionFactory(connectionFactory);

        RedisAtomicLong jobIdIndex = new RedisAtomicLong(ShareokdataManager.getRedisGlobalJobIdSchema(),
                redisTemplate.getConnectionFactory());

        jobIdCount = jobIdIndex.incrementAndGet();
        final String jobId = String.valueOf(jobIdCount);
        final String uidStr = String.valueOf(uid);
        final String jobTypeStr = String.valueOf(jobType);
        final Date startTime = new Date();

        List<Object> results = redisTemplate.execute(new SessionCallback<List<Object>>() {
            @Override
            public List<Object> execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                operations.boundHashOps("job:" + jobId);
                operations.opsForHash().put("job:" + jobId, "userId", uidStr);
                operations.opsForHash().put("job:" + jobId, "jobId", jobId);
                operations.opsForHash().put("job:" + jobId, "status", "4");
                operations.opsForHash().put("job:" + jobId, "type", jobTypeStr);
                operations.opsForHash().put("job:" + jobId, "startTime",
                        ShareokdataManager.getSimpleDateFormat().format(startTime));
                operations.opsForHash().put("job:" + jobId, "endTime", "");
                if (null != values && values.size() > 0) {
                    for (String key : values.keySet()) {
                        String value = (null != values.get(key)) ? (String) values.get(key) : "";
                        operations.opsForHash().put("job:" + jobId, key, value);
                    }
                }

                operations.boundSetOps("user_" + uidStr + "_job_set").add(jobId);

                List<Object> jobList = operations.exec();
                if (!jobList.get(0).equals(true)) {
                    operations.discard();
                }
                return jobList;
            }

        });
        newJob.setJobId(jobIdCount);
        newJob.setType(jobType);
        newJob.setStartTime(startTime);
        newJob.setUserId(uid);
        newJob.setData(values);
    } catch (Exception ex) {
        logger.error("Cannot start a new job.", ex);
    }
    return newJob;
}

From source file:com.greenline.guahao.biz.manager.cache.hrs.DepartmentCacheManager.java

/**
 * //  w  w  w  .j a  v  a2 s. c  o m
 * 
 * @param hospitalId
 * @param list
 */
public void setHospitalDepts(String hospitalId, final List<HospitalDepartmentDO> list) {
    if (hospitalId == null || list == null || list.isEmpty()) {
        return;
    }
    // 
    final RedisList<String> hDepts = hospitalDepts(hospitalId);
    // 
    hDepts.clear();
    // 
    hDepts.getOperations().execute(new SessionCallback<Object>() {
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public Object execute(RedisOperations operations) throws DataAccessException {
            operations.watch(hDepts.getKey());
            operations.multi();
            for (HospitalDepartmentDO obj : list) {
                hDepts.add(obj.getId());
            }
            operations.exec();
            return null;
        }
    });
    setExpire(hDepts);
    // ?
    for (HospitalDepartmentDO obj : list) {
        setHospitalDept(obj.getId(), obj);
    }
}