Java Code Examples for redis.clients.jedis.Pipeline#expire()

The following examples show how to use redis.clients.jedis.Pipeline#expire() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultCacheManager.java    From FATE-Serving with Apache License 2.0 5 votes vote down vote up
private void putIntoRedisCache(String cacheKey, CacheValueConfig cacheValueConfig, Object returnResult) {
    try (Jedis jedis = jedisPool.getResource()) {
        Pipeline redisPipeline = jedis.pipelined();
        redisPipeline.select(cacheValueConfig.getDbIndex());
        redisPipeline.set(cacheKey, JSON.toJSONString(returnResult));
        redisPipeline.expire(cacheKey, cacheValueConfig.getTtl());
        redisPipeline.sync();


    }
}
 
Example 2
Source File: ShardedJedisCacheManager.java    From AutoLoadCache with Apache License 2.0 5 votes vote down vote up
@Override
public void hset(byte[] key, byte[] field, byte[] value, int seconds) {
    Jedis jedis = shardedJedis.getShard(key);
    Pipeline pipeline = jedis.pipelined();
    pipeline.hset(key, field, value);
    pipeline.expire(key, seconds);
    pipeline.sync();
}
 
Example 3
Source File: MailMessageManager.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Push an string into the Redis list and update the expire seconds.
 * If the count of the list exceeds 'maxListCount', all the old content
 * are trimmed.
 * 
 * @param subject
 * @param content
 */
public void pushValueInList(String list, String content, int maxListCount, int expireSeconds) {
	Jedis jedisDB = JedisFactory.getJedisDB();
	Pipeline pipeline = jedisDB.pipelined();
	pipeline.lpush(list, content);
	if ( maxListCount > 0 ) {
		pipeline.ltrim(list, 0, maxListCount-1);
	}
	//update the expire seconds if exist
	if ( expireSeconds > 0 ) {
		pipeline.expire(list, expireSeconds);
	}
	pipeline.sync();
}
 
Example 4
Source File: RedisCacheService.java    From commafeed with Apache License 2.0 5 votes vote down vote up
@Override
public void setLastEntries(Feed feed, List<String> entries) {
	try (Jedis jedis = pool.getResource()) {
		String key = buildRedisEntryKey(feed);

		Pipeline pipe = jedis.pipelined();
		pipe.del(key);
		for (String entry : entries) {
			pipe.sadd(key, entry);
		}
		pipe.expire(key, (int) TimeUnit.DAYS.toSeconds(7));
		pipe.sync();
	}
}
 
Example 5
Source File: RedisCacheService.java    From commafeed with Apache License 2.0 5 votes vote down vote up
@Override
public void setUserRootCategory(User user, Category category) {
	try (Jedis jedis = pool.getResource()) {
		String key = buildRedisUserRootCategoryKey(user);

		Pipeline pipe = jedis.pipelined();
		pipe.del(key);
		pipe.set(key, MAPPER.writeValueAsString(category));
		pipe.expire(key, (int) TimeUnit.MINUTES.toSeconds(30));
		pipe.sync();
	} catch (JsonProcessingException e) {
		log.error(e.getMessage(), e);
	}
}
 
Example 6
Source File: RedisCacheService.java    From commafeed with Apache License 2.0 5 votes vote down vote up
@Override
public void setUnreadCount(FeedSubscription sub, UnreadCount count) {
	try (Jedis jedis = pool.getResource()) {
		String key = buildRedisUnreadCountKey(sub);

		Pipeline pipe = jedis.pipelined();
		pipe.del(key);
		pipe.set(key, MAPPER.writeValueAsString(count));
		pipe.expire(key, (int) TimeUnit.MINUTES.toSeconds(30));
		pipe.sync();
	} catch (Exception e) {
		log.error(e.getMessage(), e);
	}
}
 
Example 7
Source File: RedisTarget.java    From datacollector with Apache License 2.0 4 votes vote down vote up
private void doBatch(Batch batch) throws StageException {
  Iterator<Record> records = batch.getRecords();
  List<ErrorRecord> tempRecord = new ArrayList<>();
  Pipeline p;

  try {
    p = jedis.pipelined();

    while (records.hasNext()) {
      Record record = records.next();
      for (RedisFieldMappingConfig parameters : conf.redisFieldMapping) {
        String key = null;
        // Special treatment is only given to deletes -
        // all other records will be handled as an upsert.
        if (OperationType.DELETE_CODE == getOperationFromHeader(record)) {
          key = getDeleteKey(record, parameters);
          doDeleteRecord(record, tempRecord, p, key);
          continue;
        }

        if (record.has(parameters.keyExpr)) {
          key = record.get(parameters.keyExpr).getValueAsString();
        }
        Field value = record.get(parameters.valExpr);

        if (key != null && value != null) {
          switch (parameters.dataType) {
            case STRING:
              doUpsertString(record, tempRecord, p, key, value);
              break;
            case LIST:
              doUpsertList(record, tempRecord, p, key, value);
              break;
            case SET:
              doUpsertSet(record, tempRecord, p, key, value);
              break;
            case HASH:
              doUpsertHash(record, tempRecord, p, key, value);
              break;
            default:
              LOG.error(Errors.REDIS_05.getMessage(), parameters.dataType);
              errorRecordHandler.onError(new OnRecordErrorException(record, Errors.REDIS_05, parameters.dataType));
              break;
          }
        } else {
          LOG.warn(Errors.REDIS_07.getMessage(), parameters.keyExpr, parameters.valExpr, record);
        }

        // set the expire time
        if (parameters.ttl > 0) {
          p.expire(key, parameters.ttl);
        }
      }
    }

    List<Object> results = p.syncAndReturnAll();

    int index = 0;
    for (Object result : results) {
      if (!("OK".equals(result) || Long.class.equals(result == null ? null : result.getClass()))) {
        LOG.error(
            Errors.REDIS_03.getMessage(),
            tempRecord.get(index).operation,
            tempRecord.get(index).key,
            tempRecord.get(index).value
        );
        errorRecordHandler.onError(new OnRecordErrorException(
            tempRecord.get(index).record,
            Errors.REDIS_03,
            tempRecord.get(index).operation,
            tempRecord.get(index).key,
            tempRecord.get(index).value,
            result.toString()
        ));
      }
      index++;
    }
    retries = 0;
  } catch (JedisException ex) {
    handleException(ex, batch, tempRecord);
  }
}
 
Example 8
Source File: RewardManager.java    From gameserver with Apache License 2.0 4 votes vote down vote up
/**
	 * User takes the current available online reward.
	 * @param user
	 * @param currentTimeMillis
	 * @return
	 */
	public boolean takeOnlineReward(User user, long currentTimeMillis) {
		boolean success = false;
		if ( user == null ) {
			logger.warn("#takeOnlineReward: null user");
			return success;
		}
//		String userName = user.getUsername();
		Jedis jedisDB = JedisFactory.getJedisDB();
		String userOnlineRewardKey = getDailyMarkRewardKeyName(user.getUsername());

		String currentDate = jedisDB.hget(userOnlineRewardKey, OnlineRewardField.currentdate.name());
		String today = DateUtil.getToday(currentTimeMillis);
		
		if ( currentDate == null ) {
			processOnlineReward(user, currentTimeMillis);
			return false;
		} else if ( !today.equals(currentDate) ) {
			processOnlineReward(user, currentTimeMillis);
		}
		//Check again.
		currentDate = jedisDB.hget(userOnlineRewardKey, OnlineRewardField.currentdate.name());
		if ( today.equals(currentDate) ) {
			String stepIdStr = jedisDB.hget(userOnlineRewardKey, OnlineRewardField.stepid.name());
			String taken = jedisDB.hget(userOnlineRewardKey, OnlineRewardField.taken.name());
			String timeClock = jedisDB.hget(userOnlineRewardKey, OnlineRewardField.timeclock.name());
			
			boolean isTaken = false;
			if ( taken != null ) {
				logger.info("User {} already take the reward for timeclock: ", user.getRoleName(), timeClock);
				isTaken = true;
			}
			
			int stepId = StringUtil.toInt(stepIdStr, 0);
			int seconds = DateUtil.getSecondsToTimeClock(currentTimeMillis, timeClock);
			if ( seconds <= 0 ) {
				logger.debug("It is available to take the reward for timeclock:{}", timeClock);
				
				if ( !isTaken ) {
					//Update next timeclock
					String[] timeclocks = GameDataManager.getInstance().getGameDataAsStringArray(GameDataKey.USER_ONLINE_REWARD_STEP);
					timeClock = null;
					for ( int i = 0; i<timeclocks.length; i++ ) {
						String step = timeclocks[i];
						seconds = DateUtil.getSecondsToTimeClock(currentTimeMillis, step);
						if ( seconds > 0 ) {
							timeClock = step;
							break;
						}
					}
					
					//Delete the old data if exist
					jedisDB.del(userOnlineRewardKey);
					if ( seconds <= 0 ) {
						logger.info("User {} already finished all timeclocks in today: {}", user.getRoleName());
					}
					
					Pipeline pipeline = jedisDB.pipelined();
					pipeline.hset(userOnlineRewardKey, OnlineRewardField.currentdate.name(), today);
					pipeline.hset(userOnlineRewardKey, OnlineRewardField.stepid.name(), String.valueOf(stepId+1));
					/**
					 * When the time is after 23:30 and before 0:0, there is no valid next timeclock
					 * so the timeclock will be null. However, we need the 'taken' field to record if
					 * users already take the reward before that time.
					 */
					if ( timeClock != null ) {
						pipeline.hset(userOnlineRewardKey, OnlineRewardField.timeclock.name(), timeClock);
					} else {
						pipeline.hset(userOnlineRewardKey, OnlineRewardField.taken.name(), Constant.ONE);
					}
					pipeline.expire(userOnlineRewardKey, ONLINE_REWARD_EXPIRE);
					pipeline.sync();
					
					//Generate the new rewards for next time clock.
					if ( timeClock != null ) {
						ScriptResult result = ScriptManager.getInstance().runScript(ScriptHook.USER_ONLINE_REWARD, user, 0);
						if ( result.getType() == ScriptResult.Type.SUCCESS_RETURN ) {
							ArrayList<Reward> rewards = (ArrayList<Reward>)result.getResult();
							user.setOnlineRewards(rewards);
						}
					} else {
						user.setOnlineRewards(null);
					}
										
					success = true;
				}
			} else {
				logger.info("User {} cannot take reward because the timer does not reach: {}", 
						user.getRoleName(), timeClock);
				success = false;
			}
		}
		
		return success;
	}