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

The following examples show how to use redis.clients.jedis.Pipeline#hset() . 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: JedisPoolStream.java    From RedisDirectory with Apache License 2.0 6 votes vote down vote up
@Override
public void rename(String fileLengthKey, String fileDataKey, String oldField, String newField, List<byte[]> values, long
        fileLength) {
    long blockSize = 0;
    Jedis jedis = null;
    try {
        jedis = jedisPool.getResource();
        Pipeline pipelined = jedis.pipelined();
        //add new file length
        pipelined.hset(fileLengthKey.getBytes(), newField.getBytes(), Longs.toByteArray(fileLength));
        //add new file content
        blockSize = getBlockSize(fileLength);
        for (int i = 0; i < blockSize; i++) {
            pipelined.hset(fileDataKey.getBytes(), getBlockName(newField, i), compressFilter(values.get(i)));
        }
        values.clear();
        pipelined.sync();
    } finally {
        jedis.close();
        deleteFile(fileLengthKey, fileDataKey, oldField, blockSize);
    }
}
 
Example 2
Source File: BceChatHandlerTest.java    From gameserver with Apache License 2.0 6 votes vote down vote up
private void registerFakeSession(int count, User user) {
	//Clean all sessions
	Jedis jedis = JedisFactory.getJedis();
	Pipeline pipeline = jedis.pipelined();
	Set<byte[]> strs = jedis.keys("*".getBytes());
	for ( byte[] key : strs ) {
		pipeline.del(key);
	}
	pipeline.sync();
	
	UserId userId = user.get_id();
	SessionKey sessionKey = SessionKey.createSessionKeyFromRandomString();
	user.setSessionKey(sessionKey);
	
	//Store it with machineid to redis
	jedis = JedisFactory.getJedis();
	pipeline = jedis.pipelined();
	for ( int i=0; i<count; i++ ) {
		pipeline.hset(sessionKey.toString(), SessionManager.H_MACHINE_KEY, "localhost:10000");
		pipeline.hset(userId.toString(), SessionManager.H_MACHINE_KEY, "localhost:10000");
		pipeline.hset(userId.toString(), SessionManager.H_SESSION_KEY, sessionKey.toString());
	}
	pipeline.sync();
}
 
Example 3
Source File: RedisTarget.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void doUpsertHash(Record record, List<ErrorRecord> tempRecords, Pipeline pipeline, String key, Field value)
    throws StageException {
  if (value != null && value.getType().isOneOf(Field.Type.MAP, Field.Type.LIST_MAP)) {
    Map<String, Field> values = value.getValueAsMap();
    for (Map.Entry<String, Field> entry : values.entrySet()) {
      String fieldName = entry.getKey();
      String val = entry.getValue().getValueAsString();
      pipeline.hset(key, fieldName, val);
      tempRecords.add(new ErrorRecord(record, "Hash", key, val));
    }
  } else {
    LOG.error(Errors.REDIS_04.getMessage(), value.getType(), "value should be Map");
    errorRecordHandler.onError(
        new OnRecordErrorException(
            record,
            Errors.REDIS_04,
            value.getType(),
            "value should be Map"
        )
    );
  }
}
 
Example 4
Source File: JedisStream.java    From RedisDirectory with Apache License 2.0 6 votes vote down vote up
@Override
public void saveFile(String fileLengthKey, String fileDataKey, String fileName, List<byte[]> values, long fileLength) {
    Jedis jedis = openJedis();
    Pipeline pipelined = jedis.pipelined();
    pipelined.hset(fileLengthKey.getBytes(), fileName.getBytes(), Longs.toByteArray(fileLength));
    Long blockSize = getBlockSize(fileLength);
    for (int i = 0; i < blockSize; i++) {
        pipelined.hset(fileDataKey.getBytes(), getBlockName(fileName, i), compressFilter(values.get(i)));
        if (i % Constants.SYNC_COUNT == 0) {
            pipelined.sync();
            pipelined = jedis.pipelined();
        }
    }
    pipelined.sync();
    jedis.close();
    values.clear();
}
 
Example 5
Source File: JedisStream.java    From RedisDirectory with Apache License 2.0 6 votes vote down vote up
@Override
public void rename(String fileLengthKey, String fileDataKey, String oldField, String newField, List<byte[]> values, long
        fileLength) {
    Jedis jedis = openJedis();
    Pipeline pipelined = jedis.pipelined();
    //add new file length
    pipelined.hset(fileLengthKey.getBytes(), newField.getBytes(), Longs.toByteArray(fileLength));
    //add new file content
    Long blockSize = getBlockSize(fileLength);
    for (int i = 0; i < blockSize; i++) {
        pipelined.hset(fileDataKey.getBytes(), getBlockName(newField, i), compressFilter(values.get(i)));
    }
    pipelined.sync();
    jedis.close();
    values.clear();
    deleteFile(fileLengthKey, fileDataKey, oldField, blockSize);
}
 
Example 6
Source File: JedisPoolStream.java    From RedisDirectory with Apache License 2.0 6 votes vote down vote up
@Override
public void saveFile(String fileLengthKey, String fileDataKey, String fileName, List<byte[]> values, long fileLength) {
    Jedis jedis = null;
    try {
        jedis = jedisPool.getResource();
        Pipeline pipelined = jedis.pipelined();
        pipelined.hset(fileLengthKey.getBytes(), fileName.getBytes(), Longs.toByteArray(fileLength));
        Long blockSize = getBlockSize(fileLength);
        for (int i = 0; i < blockSize; i++) {
            pipelined.hset(fileDataKey.getBytes(), getBlockName(fileName, i), compressFilter(values.get(i)));
            if (i % Constants.SYNC_COUNT == 0) {
                pipelined.sync();
                pipelined = jedis.pipelined();
            }
        }
        values.clear();
        pipelined.sync();
    } finally {
        jedis.close();
    }
}
 
Example 7
Source File: JedisPoolStream.java    From RedisDirectory with Apache License 2.0 6 votes vote down vote up
@Override
public void rename(String fileLengthKey, String fileDataKey, String oldField, String newField, List<byte[]> values, long
        fileLength) {
    long blockSize = 0;
    Jedis jedis = null;
    try {
        jedis = jedisPool.getResource();
        Pipeline pipelined = jedis.pipelined();
        //add new file length
        pipelined.hset(fileLengthKey.getBytes(), newField.getBytes(), Longs.toByteArray(fileLength));
        //add new file content
        blockSize = getBlockSize(fileLength);
        for (int i = 0; i < blockSize; i++) {
            pipelined.hset(fileDataKey.getBytes(), getBlockName(newField, i), compressFilter(values.get(i)));
        }
        values.clear();
        pipelined.sync();
    } finally {
        jedis.close();
        deleteFile(fileLengthKey, fileDataKey, oldField, blockSize);
    }
}
 
Example 8
Source File: JedisStream.java    From RedisDirectory with Apache License 2.0 6 votes vote down vote up
@Override
public void saveFile(String fileLengthKey, String fileDataKey, String fileName, List<byte[]> values, long fileLength) {
    Jedis jedis = openJedis();
    Pipeline pipelined = jedis.pipelined();
    pipelined.hset(fileLengthKey.getBytes(), fileName.getBytes(), Longs.toByteArray(fileLength));
    Long blockSize = getBlockSize(fileLength);
    for (int i = 0; i < blockSize; i++) {
        pipelined.hset(fileDataKey.getBytes(), getBlockName(fileName, i), compressFilter(values.get(i)));
        if (i % Constants.SYNC_COUNT == 0) {
            pipelined.sync();
            pipelined = jedis.pipelined();
        }
    }
    pipelined.sync();
    jedis.close();
    values.clear();
}
 
Example 9
Source File: JedisStream.java    From RedisDirectory with Apache License 2.0 6 votes vote down vote up
@Override
public void rename(String fileLengthKey, String fileDataKey, String oldField, String newField, List<byte[]> values, long
        fileLength) {
    Jedis jedis = openJedis();
    Pipeline pipelined = jedis.pipelined();
    //add new file length
    pipelined.hset(fileLengthKey.getBytes(), newField.getBytes(), Longs.toByteArray(fileLength));
    //add new file content
    Long blockSize = getBlockSize(fileLength);
    for (int i = 0; i < blockSize; i++) {
        pipelined.hset(fileDataKey.getBytes(), getBlockName(newField, i), compressFilter(values.get(i)));
    }
    pipelined.sync();
    jedis.close();
    values.clear();
    deleteFile(fileLengthKey, fileDataKey, oldField, blockSize);
}
 
Example 10
Source File: JedisPoolStream.java    From RedisDirectory with Apache License 2.0 6 votes vote down vote up
@Override
public void saveFile(String fileLengthKey, String fileDataKey, String fileName, List<byte[]> values, long fileLength) {
    Jedis jedis = null;
    try {
        jedis = jedisPool.getResource();
        Pipeline pipelined = jedis.pipelined();
        pipelined.hset(fileLengthKey.getBytes(), fileName.getBytes(), Longs.toByteArray(fileLength));
        Long blockSize = getBlockSize(fileLength);
        for (int i = 0; i < blockSize; i++) {
            pipelined.hset(fileDataKey.getBytes(), getBlockName(fileName, i), compressFilter(values.get(i)));
            if (i % Constants.SYNC_COUNT == 0) {
                pipelined.sync();
                pipelined = jedis.pipelined();
            }
        }
        values.clear();
        pipelined.sync();
    } finally {
        jedis.close();
    }
}
 
Example 11
Source File: PipelineTest.java    From code with Apache License 2.0 6 votes vote down vote up
@Test
public void testPipeline() {
    try (Jedis jedis = new Jedis("192.168.108.129", 6379)){
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            Pipeline pipeline = jedis.pipelined();
            for (int j = i * 100; j < (i + 1) * 100; j++) {
                pipeline.hset("hashKey-" + j, "field-" + j, "value-" + j);
            }
            pipeline.syncAndReturnAll();
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时:" + (end - start)); // 耗时:108
        jedis.flushAll();//清空数据库,方便后续测试
    }
}
 
Example 12
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 13
Source File: RedisRoomManager.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
	 * Update the user's session map in Redis.
	 * 
	 * @param userSessionKey
	 * @param isAI
	 * @return
	 */
	@Override
	public boolean updateUserSessionMap(SessionKey userSessionKey, 
			SessionKey roomSessionKey, boolean isAI, Pipeline pipeline) {
		pipeline.hset(userSessionKey.toString(), H_ROOM_SESSION_KEY, roomSessionKey.toString());
//		pipeline.hset(userSessionKey.toString(), H_ISAI, V_FALSE);
		return true;
	}
 
Example 14
Source File: RedisUtil.java    From RedisBungee with Eclipse Public License 1.0 5 votes vote down vote up
public static void cleanUpPlayer(String player, Pipeline rsc) {
    rsc.srem("proxy:" + RedisBungee.getApi().getServerId() + ":usersOnline", player);
    rsc.hdel("player:" + player, "server", "ip", "proxy");
    long timestamp = System.currentTimeMillis();
    rsc.hset("player:" + player, "online", String.valueOf(timestamp));
    rsc.publish("redisbungee-data", RedisBungee.getGson().toJson(new DataManager.DataManagerMessage<>(
            UUID.fromString(player), DataManager.DataManagerMessage.Action.LEAVE,
            new DataManager.LogoutPayload(timestamp))));
}
 
Example 15
Source File: Battle.java    From gameserver with Apache License 2.0 4 votes vote down vote up
/**
 * Create a new instance of Battle object.
 * @param battleRoom
 */
public Battle(BattleRoom battleRoom, String gameServerId) {
	this.battleRoom = battleRoom;
	this.gameServerId = gameServerId;
	
	Room roomLeft = battleRoom.getRoomLeft();
	Room roomRight = battleRoom.getRoomRight();
	roomType = roomLeft.getRoomType();
			
	List<UserInfo> users1 = roomLeft.getUserInfoList();
	this.userLeftList = makeUserList(users1, roomLeft.getRoomSessionKey(), 
			roomLeft.getCurrentUserCount(), BattleCamp.LEFT.id(), roomLeft.getRoomType());
	
	List<UserInfo> users2 = roomRight.getUserInfoList();
	this.userRightList = makeUserList(users2, roomRight.getRoomSessionKey(), 
			roomRight.getCurrentUserCount(), BattleCamp.RIGHT.id(), roomRight.getRoomType());
	
	this.battleUserNumber = this.userLeftList.size() + this.userRightList.size();
	
	//Choose the mapId
	this.battleMap = chooseBattleMap(roomLeft.getMapId(), roomRight.getMapId());
	
	//Save to Redis
	String gameServerValue = null;
	if ( this.gameServerId != null ) {
		gameServerValue = this.gameServerId;
	} else {
		gameServerValue = Constant.EMPTY;
	}
	Pipeline pipeline = JedisFactory.getJedis().pipelined();
	Collection<BattleUser> battleUsers = battleUserMap.values();
	for (Iterator iter = battleUsers.iterator(); iter.hasNext();) {
		BattleUser battleUser = (BattleUser) iter.next();
		pipeline.hset(battleUser.getUserSessionKey().toString(), BATTLE_SERVER_KEY, gameServerValue);
		pipeline.hset(battleUser.getUserSessionKey().toString(), BATTLE_SESSION_KEY, 
				this.battleRoom.getSessionKey().toString());
	}
	pipeline.sync();

	//Setup relationship here
	if ( this.battleRoom.getRoomRight().getRoomType() != RoomType.PVE_ROOM ) {
		setupRelation();
	}
	
	/**
	 * Store the battle room type.
	 */
	battleRoomType = this.battleRoom.getRoomLeft().getRoomType();
}
 
Example 16
Source File: RewardManager.java    From gameserver with Apache License 2.0 4 votes vote down vote up
/**
	 * Take today's login reward. The remainTimes will be subtracted 1
	 * 
	 * @param user
	 * @param currentTimeMillis
	 * @return
	 */
	public boolean takeDailyMarkReward(User user, long currentTimeMillis) {
		boolean success = false;
		if ( user == null ) {
			logger.warn("#takeDailyMarkReward: null user");
			return success;
		}
//		String userName = user.getUsername();
		String roleName = user.getRoleName();
		Jedis jedisDB = JedisFactory.getJedisDB();
		String userDailyMarkRewardKey = getDailyMarkRewardKeyName(user.getUsername());

		String actualDay = jedisDB.hget(userDailyMarkRewardKey, DailyMarkField.currentdate.name());
		
		//Get today string
		String today = DateUtil.getToday(currentTimeMillis);

		DailyMarkReward dailyMark = null;
		if ( !today.equals(actualDay) ) {
			//Need to create the actualMonth fields in Redis
			processDailyMarkReward(user, currentTimeMillis);
			//Mark today
			String actualMonth= jedisDB.hget(userDailyMarkRewardKey, DailyMarkField.currentmonth.name());
			int todayValue = StringUtil.toInt(today.substring(today.length()-2), 1);
			int actualDayValue = 0;
			if ( actualDay != null && actualDay.length() >= 2 ) {
				actualDayValue= StringUtil.toInt(actualDay.substring(actualDay.length()-2), 1);
			}
			int dayDiff = todayValue - actualDayValue;
			//obtain mark array
			String markArrayStr = jedisDB.hget(
					userDailyMarkRewardKey, DailyMarkField.markarray.name());
			StringBuilder buf = new StringBuilder();
			if (markArrayStr != null){
				buf.append(markArrayStr).append(',');
			}
			for ( int i=0; i<dayDiff-1; i++ ) {
				buf.append('0').append(',');
			}
			//Set today's mark
			buf.append('1');
			markArrayStr = buf.toString();
			
			String totalCountStr = jedisDB.hget(
					userDailyMarkRewardKey, DailyMarkField.totalcount.name());
			int totalCount = StringUtil.toInt(totalCountStr, 1)+1;
			
			Pipeline pipeline = jedisDB.pipelined();
			pipeline.hset(
					userDailyMarkRewardKey, DailyMarkField.currentmonth.name(), actualMonth);
			pipeline.hset(
					userDailyMarkRewardKey, DailyMarkField.currentdate.name(), today);
			pipeline.hset(
					userDailyMarkRewardKey, DailyMarkField.markarray.name(), markArrayStr);
			pipeline.hset(
					userDailyMarkRewardKey, DailyMarkField.totalcount.name(), String.valueOf(totalCount));
			pipeline.sync();
			
			logger.debug("User {}'s daily mark record is updated.", roleName);
			
			dailyMark = processDailyMarkReward(user, currentTimeMillis);
			
			if ( dailyMark != null ) {
				DailyMarkPojo markPojo = dailyMark.getDailyMark();
				if ( markPojo != null ) {
					int dayNum = markPojo.getDayNum();
					String key = StringUtil.concat(DailyMarkField.taken.name(), dayNum);
					if ( !jedisDB.exists(key) ) {
						jedisDB.hset(userDailyMarkRewardKey, key, today);
						success = true;
						logger.debug("User {} takes its daily mark reward for dayNum: {}", roleName, dayNum);
					} else {
						success = false;
						logger.debug("User {} has already taken daily mark reward for dayNum: {}", roleName, dayNum);
					}
				} else {
					success = false;
					logger.debug("User {} dayNum {} does not reach the condition", 
							roleName, dailyMark.getTotalCount());
				}
			  //Call tasks
				TaskManager.getInstance().processUserTasks(user, TaskHook.LOGIN_DATE, dailyMark);
			}
		} else {
			logger.debug("User {} has already marked date:{}", roleName, today);
		}
		return success;
	}
 
Example 17
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;
	}
 
Example 18
Source File: RedisUtil.java    From RedisBungee with Eclipse Public License 1.0 4 votes vote down vote up
protected static void createPlayer(ProxiedPlayer player, Pipeline pipeline, boolean fireEvent) {
    createPlayer(player.getPendingConnection(), pipeline, fireEvent);
    if (player.getServer() != null)
        pipeline.hset("player:" + player.getUniqueId().toString(), "server", player.getServer().getInfo().getName());
}