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

The following examples show how to use redis.clients.jedis.Pipeline#sadd() . 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: JedisPipelineDemo.java    From Redis-4.x-Cookbook with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    //Connecting to localhost Redis server
    Jedis jedis = new Jedis("localhost");

    //Create a Pipeline
    Pipeline pipeline = jedis.pipelined();
    //Add commands to pipeline
    pipeline.set("mykey", "myvalue");
    pipeline.sadd("myset", "value1", "value2");
    Response<String> stringValue = pipeline.get("mykey");
    Response<Long> noElementsInSet = pipeline.scard("myset");
    //Send commands
    pipeline.sync();
    //Handle responses
    System.out.printf("mykey: %s\n", stringValue.get());
    System.out.printf("Number of Elements in set: %d\n", noElementsInSet.get());
    System.exit(0);
}
 
Example 2
Source File: RedisTarget.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void doUpsertSet(Record record, List<ErrorRecord> tempRecords, Pipeline pipeline, String key, Field value)
    throws StageException {
  if (value != null && value.getType() == Field.Type.LIST) {
    List<Field> values = value.getValueAsList();
    for (Field element : values) {
      if (element != null) {
        String val = element.getValueAsString();
        pipeline.sadd(key, val);
        tempRecords.add(new ErrorRecord(record, "Set", key, val));
      }
    }
  } else {
    LOG.error(Errors.REDIS_04.getMessage(), value.getType(), "value should be List");
    errorRecordHandler.onError(
        new OnRecordErrorException(
            record,
            Errors.REDIS_04,
            value.getType(),
            "value should be List"
        )
    );
  }
}
 
Example 3
Source File: RedisStorage.java    From quartz-redis-jobstore with Apache License 2.0 6 votes vote down vote up
/**
 * Store a job in Redis
 * @param jobDetail the {@link org.quartz.JobDetail} object to be stored
 * @param replaceExisting if true, any existing job with the same group and name as the given job will be overwritten
 * @param jedis a thread-safe Redis connection
 * @throws org.quartz.ObjectAlreadyExistsException
 */
@Override
@SuppressWarnings("unchecked")
public void storeJob(JobDetail jobDetail, boolean replaceExisting, Jedis jedis) throws ObjectAlreadyExistsException {
    final String jobHashKey = redisSchema.jobHashKey(jobDetail.getKey());
    final String jobDataMapHashKey = redisSchema.jobDataMapHashKey(jobDetail.getKey());
    final String jobGroupSetKey = redisSchema.jobGroupSetKey(jobDetail.getKey());

    if(!replaceExisting && jedis.exists(jobHashKey)){
        throw new ObjectAlreadyExistsException(jobDetail);
    }

    Pipeline pipe = jedis.pipelined();
    pipe.hmset(jobHashKey, (Map<String, String>) mapper.convertValue(jobDetail, new TypeReference<HashMap<String, String>>() {}));
    pipe.del(jobDataMapHashKey);
    if(jobDetail.getJobDataMap() != null && !jobDetail.getJobDataMap().isEmpty()){
        pipe.hmset(jobDataMapHashKey, getStringDataMap(jobDetail.getJobDataMap()));
    }

    pipe.sadd(redisSchema.jobsSet(), jobHashKey);
    pipe.sadd(redisSchema.jobGroupsSet(), jobGroupSetKey);
    pipe.sadd(jobGroupSetKey, jobHashKey);
    pipe.sync();
}
 
Example 4
Source File: JedisIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenMultipleIndependentOperations_whenNetworkOptimizationIsImportant_thenWrapThemInAPipeline() {
    String userOneId = "4352523";
    String userTwoId = "4849888";

    Pipeline p = jedis.pipelined();
    p.sadd("searched#" + userOneId, "paris");
    p.zadd("ranking", 126, userOneId);
    p.zadd("ranking", 325, userTwoId);
    Response<Boolean> pipeExists = p.sismember("searched#" + userOneId, "paris");
    Response<Set<String>> pipeRanking = p.zrange("ranking", 0, -1);
    p.sync();

    Assert.assertTrue(pipeExists.get());
    Assert.assertEquals(2, pipeRanking.get().size());
}
 
Example 5
Source File: RedisStorage.java    From quartz-redis-jobstore with Apache License 2.0 5 votes vote down vote up
/**
 * Store a {@link org.quartz.Calendar}
 * @param name the name of the calendar
 * @param calendar the calendar object to be stored
 * @param replaceExisting if true, any existing calendar with the same name will be overwritten
 * @param updateTriggers if true, any existing triggers associated with the calendar will be updated
 * @param jedis a thread-safe Redis connection
 * @throws JobPersistenceException
 */
@Override
public void storeCalendar(String name, Calendar calendar, boolean replaceExisting, boolean updateTriggers, Jedis jedis) throws JobPersistenceException{
    final String calendarHashKey = redisSchema.calendarHashKey(name);
    if(!replaceExisting && jedis.exists(calendarHashKey)){
        throw new ObjectAlreadyExistsException(String.format("Calendar with key %s already exists.", calendarHashKey));
    }
    Map<String, String> calendarMap = new HashMap<>();
    calendarMap.put(CALENDAR_CLASS, calendar.getClass().getName());
    try {
        calendarMap.put(CALENDAR_JSON, mapper.writeValueAsString(calendar));
    } catch (JsonProcessingException e) {
        throw new JobPersistenceException("Unable to serialize calendar.", e);
    }

    Pipeline pipe = jedis.pipelined();
    pipe.hmset(calendarHashKey, calendarMap);
    pipe.sadd(redisSchema.calendarsSet(), calendarHashKey);
    pipe.sync();

    if(updateTriggers){
        final String calendarTriggersSetKey = redisSchema.calendarTriggersSetKey(name);
        Set<String> triggerHashKeys = jedis.smembers(calendarTriggersSetKey);
        for (String triggerHashKey : triggerHashKeys) {
            OperableTrigger trigger = retrieveTrigger(redisSchema.triggerKey(triggerHashKey), jedis);
            long removed = jedis.zrem(redisSchema.triggerStateKey(RedisTriggerState.WAITING), triggerHashKey);
            trigger.updateWithNewCalendar(calendar, misfireThreshold);
            if(removed == 1){
                setTriggerState(RedisTriggerState.WAITING, (double) trigger.getNextFireTime().getTime(), triggerHashKey, jedis);
            }
        }
    }
}
 
Example 6
Source File: JedisTest.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public void testLongSetPerformance1_1() {
	JedisAdapter jedis = new JedisAdapter(host, port, config);

	//Store a long list
	int count = 500000;
	byte[] key = "longlist".getBytes();
	jedis.del(key);
	
	byte[][] longList = createLongList(count);
	Pipeline pipeline = jedis.pipelined();
	for ( int i=0; i<longList.length; i++ ) {
		pipeline.sadd(key, longList[i]);
	}
	pipeline.sync();
	Set<byte[]> userList = jedis.smembers(key);
	assertTrue(userList.size()>0);
	
	//Getting the list.
	long startM = 0l, endM = 0l;
	startM = System.currentTimeMillis();
	int max = 10;
	for ( int i=0; i<max; i++ ) {
		userList = jedis.smembers(key);
	}
	endM = System.currentTimeMillis();
	System.out.println("Redis longset:"+userList.size()+" loop " + max + " perform: " + (endM-startM)/max);
}
 
Example 7
Source File: RedisUtil.java    From RedisBungee with Eclipse Public License 1.0 5 votes vote down vote up
protected static void createPlayer(PendingConnection connection, Pipeline pipeline, boolean fireEvent) {
    Map<String, String> playerData = new HashMap<>(4);
    playerData.put("online", "0");
    playerData.put("ip", connection.getAddress().getAddress().getHostAddress());
    playerData.put("proxy", RedisBungee.getConfiguration().getServerId());

    pipeline.sadd("proxy:" + RedisBungee.getApi().getServerId() + ":usersOnline", connection.getUniqueId().toString());
    pipeline.hmset("player:" + connection.getUniqueId().toString(), playerData);

    if (fireEvent) {
        pipeline.publish("redisbungee-data", RedisBungee.getGson().toJson(new DataManager.DataManagerMessage<>(
                connection.getUniqueId(), DataManager.DataManagerMessage.Action.JOIN,
                new DataManager.LoginPayload(connection.getAddress().getAddress()))));
    }
}
 
Example 8
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 9
Source File: RedisEventLog.java    From concursus with MIT License 4 votes vote down vote up
private Response<Long> writeEventsForId(Pipeline pipeline, AggregateId id, List<Event> eventsForId) {
    return pipeline.sadd(id.toString(), serialiseEvents(eventsForId));
}
 
Example 10
Source File: RedisStorage.java    From quartz-redis-jobstore with Apache License 2.0 4 votes vote down vote up
/**
 * Store a trigger in redis
 * @param trigger the trigger to be stored
 * @param replaceExisting true if an existing trigger with the same identity should be replaced
 * @param jedis a thread-safe Redis connection
 * @throws JobPersistenceException
 * @throws ObjectAlreadyExistsException
 */
@Override
public void storeTrigger(OperableTrigger trigger, boolean replaceExisting, Jedis jedis) throws JobPersistenceException {
    final String triggerHashKey = redisSchema.triggerHashKey(trigger.getKey());
    final String triggerGroupSetKey = redisSchema.triggerGroupSetKey(trigger.getKey());
    final String jobTriggerSetKey = redisSchema.jobTriggersSetKey(trigger.getJobKey());

    if(!(trigger instanceof SimpleTrigger) && !(trigger instanceof CronTrigger)){
        throw new UnsupportedOperationException("Only SimpleTrigger and CronTrigger are supported.");
    }
    final boolean exists = jedis.exists(triggerHashKey);
    if(exists && !replaceExisting){
        throw new ObjectAlreadyExistsException(trigger);
    }

    Map<String, String> triggerMap = mapper.convertValue(trigger, new TypeReference<HashMap<String, String>>() {});
    triggerMap.put(TRIGGER_CLASS, trigger.getClass().getName());

    Pipeline pipe = jedis.pipelined();
    pipe.hmset(triggerHashKey, triggerMap);
    pipe.sadd(redisSchema.triggersSet(), triggerHashKey);
    pipe.sadd(redisSchema.triggerGroupsSet(), triggerGroupSetKey);
    pipe.sadd(triggerGroupSetKey, triggerHashKey);
    pipe.sadd(jobTriggerSetKey, triggerHashKey);
    if(trigger.getCalendarName() != null && !trigger.getCalendarName().isEmpty()){
        final String calendarTriggersSetKey = redisSchema.calendarTriggersSetKey(trigger.getCalendarName());
        pipe.sadd(calendarTriggersSetKey, triggerHashKey);
    }
    if (trigger.getJobDataMap() != null && !trigger.getJobDataMap().isEmpty()) {
        final String triggerDataMapHashKey = redisSchema.triggerDataMapHashKey(trigger.getKey());
        pipe.hmset(triggerDataMapHashKey, getStringDataMap(trigger.getJobDataMap()));
    }
    pipe.sync();

    if(exists){
        // We're overwriting a previously stored instance of this trigger, so clear any existing trigger state.
        unsetTriggerState(triggerHashKey, jedis);
    }

    pipe = jedis.pipelined();
    Response<Boolean> triggerPausedResponse = pipe.sismember(redisSchema.pausedTriggerGroupsSet(), triggerGroupSetKey);
    Response<Boolean> jobPausedResponse = pipe.sismember(redisSchema.pausedJobGroupsSet(), redisSchema.jobGroupSetKey(trigger.getJobKey()));
    pipe.sync();
    final String jobHashKey = redisSchema.jobHashKey(trigger.getJobKey());
    final long nextFireTime = trigger.getNextFireTime() != null ? trigger.getNextFireTime().getTime() : -1;
    if (triggerPausedResponse.get() || jobPausedResponse.get()){
        if (isBlockedJob(jobHashKey, jedis)) {
            setTriggerState(RedisTriggerState.PAUSED_BLOCKED, (double) nextFireTime, triggerHashKey, jedis);
        } else {
            setTriggerState(RedisTriggerState.PAUSED, (double) nextFireTime, triggerHashKey, jedis);
        }
    } else if(trigger.getNextFireTime() != null){
        if (isBlockedJob(jobHashKey, jedis)) {
            setTriggerState(RedisTriggerState.BLOCKED, nextFireTime, triggerHashKey, jedis);
        } else {
            setTriggerState(RedisTriggerState.WAITING, (double) trigger.getNextFireTime().getTime(), triggerHashKey, jedis);
        }
    }
}
 
Example 11
Source File: TaskManager.java    From gameserver with Apache License 2.0 4 votes vote down vote up
/**
	 * An user finish a task. The task id will be removed from todo set
	 * and added to finished set.
	 * 
	 * @param user
	 * @param taskId
	 * @return
	 */
	public boolean finishTask(User user, String taskId) {
		//Get the persistent Jedis instance
		boolean result = true;
		Jedis jedisDB = JedisFactory.getJedisDB();
		String todoSet = getTodoSetName(user);
		String finishedSet = getFinishedSetName(user);
		
		//Delete it from todo list and add it to finish list
		Pipeline pipeline = jedisDB.pipelined();
		pipeline.srem(todoSet, taskId);
		pipeline.sadd(finishedSet, taskId);
		pipeline.sync();
		
		//Delete all data related to the task
		deleteTaskData(user, taskId);
				
		//Remove from user's tasklist if exist
		TaskPojo task = this.getTaskById(taskId);
		user.removeTask(task);
		user.addTaskFinished(task);
		
		if ( task.getType() == TaskType.TASK_ACHIVEMENT ) {
			this.takeTaskReward(user, taskId, 0);
			if ( task.isBroadcast() ) {
				String roleName = UserManager.getDisplayRoleName(user.getRoleName());
				String content = Text.text("notice.achievement", roleName, task.getName());
				ChatManager.getInstance().processChatToWorldAsyn(null, content);
			}
		} else {
			boolean success = false;
			if ( task.getType() == TaskType.TASK_ACTIVITY && 
					StringUtil.checkNotEmpty(task.getGiftDesc()) ) {
				success = this.takeTaskReward(user, taskId, 0);
			}
//			if ( success && task.isBroadcast() ) {
//				String roleName = UserManager.getDisplayRoleName(user.getRoleName());
//				String content = Text.text("notice.task", roleName, task.getName());
//				ChatManager.getInstance().processChatToWorldAsyn(null, content);
//			}
		}
//		boolean alreadyFinished = jedisDB.sismember(finishedSet, taskId);
//		if ( alreadyFinished ) {	
//			logger.debug("#finishTask: The task(id:{}) is already finished.", taskId);
//			return false;
//		} else {
//
//		}
		
		//Send the BseModiTask to client
		//Move this block of code the script.task.Step#step() method
		//wangqi 2012-02-09
		/*
		BseModiTask.Builder modiBuilder = BseModiTask.newBuilder();
		modiBuilder.setTaskID(StringUtil.toInt(taskId, 0));
		modiBuilder.setStep(task.getStep());
		XinqiMessage xinqiMsg = new XinqiMessage();
		xinqiMsg.payload = modiBuilder.build();
		
		GameContext.getInstance().writeResponse(user.getSession(), xinqiMsg);
		*/
		
		logger.debug("User {} finish the task(id:{}).", user.getRoleName(), taskId);
		
		return result;
	}