org.springframework.data.redis.connection.Message Java Examples

The following examples show how to use org.springframework.data.redis.connection.Message. 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: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    connection.publish("test".getBytes(), "msg".getBytes());
}
 
Example #2
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    
}
 
Example #3
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    connection.publish("test".getBytes(), "msg".getBytes());
}
 
Example #4
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    
}
 
Example #5
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    connection.publish("test".getBytes(), "msg".getBytes());
}
 
Example #6
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    
}
 
Example #7
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    connection.publish("test".getBytes(), "msg".getBytes());
}
 
Example #8
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    
}
 
Example #9
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            System.out.println("message " + new String(message.getBody()));
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    connection.publish("test".getBytes(), "msg".getBytes());
}
 
Example #10
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    
}
 
Example #11
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    connection.publish("test".getBytes(), "msg".getBytes());
}
 
Example #12
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    connection.publish("test".getBytes(), "msg".getBytes());
}
 
Example #13
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    
}
 
Example #14
Source File: RedisSagaEventConsumer.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
@Override
public void onMessage(Message message, byte[] pattern) {
  if (nodeStatus.isMaster()) {
    messageSerializer.deserialize(message.getBody()).ifPresent(data -> {
      BaseEvent event = (BaseEvent) data;
      if (LOG.isDebugEnabled()) {
        LOG.debug("event = [{}]", event);
      }
      try {
        long begin = System.currentTimeMillis();
        metricsService.metrics().doActorReceived();
        sagaShardRegionActor.tell(event, sagaShardRegionActor);
        long end = System.currentTimeMillis();
        metricsService.metrics().doActorAccepted();
        metricsService.metrics().doActorAvgTime(end - begin);
      } catch (Exception e) {
        metricsService.metrics().doActorRejected();
        LOG.error("subscriber Exception = [{}]", e.getMessage(), e);
      }
    });
  }
}
 
Example #15
Source File: MessageScheduler.java    From rqueue with Apache License 2.0 6 votes vote down vote up
@Override
public void onMessage(Message message, byte[] pattern) {
  if (message.getBody().length == 0 || message.getChannel().length == 0) {
    return;
  }
  String body = new String(message.getBody());
  String channel = new String(message.getChannel());
  getLogger().debug("Body: {} Channel: {}", body, channel);
  try {
    Long startTime = Long.parseLong(body);
    String queueName = channelNameToQueueName.get(channel);
    if (queueName == null) {
      getLogger().warn("Unknown channel name {}", channel);
      return;
    }
    schedule(queueName, startTime, false);
  } catch (Exception e) {
    getLogger().error("Error occurred on a channel {}, body: {}", channel, body, e);
  }
}
 
Example #16
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    
}
 
Example #17
Source File: CacheConfig.java    From springboot-plus with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Bean
MessageListenerAdapter listenerAdapter(final TowLevelCacheManager cacheManager) {
	return new MessageListenerAdapter(new MessageListener() {

		public void onMessage(Message message, byte[] pattern) {
			byte[] bs = message.getChannel();
			try {
				// Sub 一个消息,通知缓存管理器
				String type = new String(bs, "UTF-8");
				cacheManager.receiver(type);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				// 不可能出错,忽略
			}

		}

	});
}
 
Example #18
Source File: SpringRedisActiveMessageListener.java    From J2Cache with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message message, byte[] pattern) {
	String key = message.toString();
	if (key == null) {
		return;
	}
	if (key.startsWith(namespace + ":")) {
		String[] k = key.replaceFirst(namespace + ":", "").split(":", 2);
		if(k.length != 2) {
			return;
		}
		clusterPolicy.evict(k[0], k[1]);
	}

}
 
Example #19
Source File: CacheMessageListener.java    From tools with MIT License 5 votes vote down vote up
@Override
public void onMessage(Message message, byte[] bytes) {
    cn.gjing.tools.cache.Message message1 = (cn.gjing.tools.cache.Message) this.redisTemplate.getValueSerializer().deserialize(message.getBody());
    if (message1 == null) {
        return;
    }
    toolsCacheManager.clearLocal(message1.getCacheName(), message1.getKey());
}
 
Example #20
Source File: SpringRedisActiveMessageListener.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Override
public void onMessage(Message message, byte[] pattern) {
    String key = message.toString();
    if (key == null) {
        return;
    }
    if (key.startsWith(namespace + ":")) {
        String[] k = key.replaceFirst(namespace + ":", "").split(":", 2);
        if (k.length != 2) {
            return;
        }
        clusterPolicy.evict(k[0], k[1]);
    }
}
 
Example #21
Source File: SpringRedisMessageListener.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Override
public void onMessage(Message message, byte[] pattern) {
    byte[] messageChannel = message.getChannel();
    byte[] messageBody = message.getBody();
    if (messageChannel == null || messageBody == null) {
        return;
    }
    try {
        Command cmd = Command.parse(String.valueOf(SerializationUtils.deserialize(messageBody)));
        if (cmd == null || isLocalCommand(cmd)) { return; }

        switch (cmd.getOperator()) {
            case Command.OPT_JOIN:
                logger.info("Node-" + cmd.getSrc() + " joined to " + this.channel);
                break;
            case Command.OPT_EVICT_KEY:
                clusterPolicy.evict(cmd.getRegion(), cmd.getKeys());
                logger.debug("Received cache evict message, region=" + cmd.getRegion() + ",key="
                    + String.join(",", cmd.getKeys()));
                break;
            case Command.OPT_CLEAR_KEY:
                clusterPolicy.clear(cmd.getRegion());
                logger.debug("Received cache clear message, region=" + cmd.getRegion());
                break;
            case Command.OPT_QUIT:
                logger.info("Node-" + cmd.getSrc() + " quit to " + this.channel);
                break;
            default:
                logger.warn("Unknown message type = " + cmd.getOperator());
        }
    } catch (Exception e) {
        logger.error("Failed to handle received msg", e);
    }
}
 
Example #22
Source File: RedisMessageListener.java    From spring-cloud-shop with MIT License 5 votes vote down vote up
@Override
public void onMessage(@NonNull Message message, @Nullable byte[] pattern) {

    byte[] body = message.getBody();//请使用valueSerializer
    byte[] channel = message.getChannel();
    String msg = stringRedisSerializer.deserialize(body);
    String topic = stringRedisSerializer.deserialize(channel);
    System.out.println("我是sub,监听" + topic + ",我收到消息:" + msg);

}
 
Example #23
Source File: SpringRedisMessageListener.java    From J2Cache with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message message, byte[] pattern) {
	byte[] messageChannel = message.getChannel();
	byte[] messageBody = message.getBody();
	if (messageChannel == null || messageBody == null) {
		return;
	}
       try {
           Command cmd = Command.parse(String.valueOf(SerializationUtils.deserialize(messageBody)));
           if (cmd == null || isLocalCommand(cmd))
               return;

           switch (cmd.getOperator()) {
               case Command.OPT_JOIN:
               	logger.info("Node-"+cmd.getSrc()+" joined to " + this.channel);
                   break;
               case Command.OPT_EVICT_KEY:
               	clusterPolicy.evict(cmd.getRegion(), cmd.getKeys());
                   logger.debug("Received cache evict message, region=" + cmd.getRegion() + ",key=" + String.join(",", cmd.getKeys()));
                   break;
               case Command.OPT_CLEAR_KEY:
               	clusterPolicy.clear(cmd.getRegion());
                   logger.debug("Received cache clear message, region=" + cmd.getRegion());
                   break;
               case Command.OPT_QUIT:
               	logger.info("Node-"+cmd.getSrc()+" quit to " + this.channel);
                   break;
               default:
               	logger.warn("Unknown message type = " + cmd.getOperator());
           }
       } catch (Exception e) {
       	logger.error("Failed to handle received msg", e);
       }
}
 
Example #24
Source File: TokenRepositoryImpl.java    From authlib-agent with MIT License 5 votes vote down vote up
@PostConstruct
private void registerExpiredEventListener() {
	expiredListener = new MessageListener() {

		@Override
		public void onMessage(Message message, byte[] pattern) {
			byte[] body = message.getBody();
			if (body == null) {
				return;
			}

			String key;
			try {
				key = new String(message.getBody(), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				LOGGER.debug(() -> "failed to decode message body: " + bytesToHex(body), e);
				return;
			}

			if (!key.startsWith(PREFIX_EXPIRE)) {
				return;
			}

			String accessToken = key.substring(PREFIX_EXPIRE.length());
			template.delete(keyAccessToken(accessToken));
			Map<String, String> values = hashOps.entries(keyAccessToken(accessToken));
			if (values != null && !values.isEmpty()) {
				setOps.remove(keyClientToken(values.get(KEY_CLIENT_TOKEN)), accessToken);
				setOps.remove(keyAccount(values.get(KEY_OWNER)), accessToken);
			}
		}
	};
	container.addMessageListener(expiredListener, new PatternTopic("__keyevent@*__:expired"));
}
 
Example #25
Source File: SimpleReceiver.java    From spring-boot-tutorials with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message message, byte[] pattern) {
    String channel = StringRedisSerializer.UTF_8.deserialize(message.getChannel());

    String body = StringRedisSerializer.UTF_8.deserialize(message.getBody());

    logger.info("Receive channel:{}, body:{}", channel, body);
}
 
Example #26
Source File: SpringRedisActiveMessageListener.java    From J2Cache with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message message, byte[] pattern) {
	String key = message.toString();
	if (key == null) {
		return;
	}
	if (key.startsWith(namespace + ":")) {
		String[] k = key.replaceFirst(namespace + ":", "").split(":", 2);
		if(k.length != 2) {
			return;
		}
		clusterPolicy.evict(k[0], k[1]);
	}

}
 
Example #27
Source File: TieBaNoImageIdMessageListener.java    From javabase with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message message, byte[] bytes) {
	String jsonStr = WebmagicService.getString(message.getBody());
	ContentBean contentBean = JSONObject.parseObject(jsonStr, ContentBean.class);
	redisTemplate.execute(new RedisCallback<Object>() {
		@Override
		public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
			byte[] key = getByte(TIEBA_CONTENT_NO_IMAGE_KEY + contentBean.getName());
			redisConnection.sAdd(key, getByte(contentBean.getId()));
			return null;
		}
	});
}
 
Example #28
Source File: SpringRedisMessageListener.java    From J2Cache with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message message, byte[] pattern) {
	byte[] messageChannel = message.getChannel();
	byte[] messageBody = message.getBody();
	if (messageChannel == null || messageBody == null) {
		return;
	}
       try {
           Command cmd = Command.parse(String.valueOf(SerializationUtils.deserialize(messageBody)));
           if (cmd == null || isLocalCommand(cmd))
               return;

           switch (cmd.getOperator()) {
               case Command.OPT_JOIN:
               	logger.info("Node-"+cmd.getSrc()+" joined to " + this.channel);
                   break;
               case Command.OPT_EVICT_KEY:
               	clusterPolicy.evict(cmd.getRegion(), cmd.getKeys());
                   logger.debug("Received cache evict message, region=" + cmd.getRegion() + ",key=" + String.join(",", cmd.getKeys()));
                   break;
               case Command.OPT_CLEAR_KEY:
               	clusterPolicy.clear(cmd.getRegion());
                   logger.debug("Received cache clear message, region=" + cmd.getRegion());
                   break;
               case Command.OPT_QUIT:
               	logger.info("Node-"+cmd.getSrc()+" quit to " + this.channel);
                   break;
               default:
               	logger.warn("Unknown message type = " + cmd.getOperator());
           }
       } catch (Exception e) {
       	logger.error("Failed to handle received msg", e);
       }
}
 
Example #29
Source File: TaxiBookingAcceptedEventMessageListener.java    From Spring-Boot-2.0-Projects with MIT License 5 votes vote down vote up
@Override
public void onMessage(Message message, @Nullable byte[] bytes) {
    try {
        TaxiBookingAcceptedEventDTO taxiBookingAcceptedEventDTO = objectMapper.readValue(new String(message.getBody()), TaxiBookingAcceptedEventDTO.class);
        LOGGER.info("Accepted Event {}", taxiBookingAcceptedEventDTO);
        taxiService.updateTaxiStatus(taxiBookingAcceptedEventDTO.getTaxiId(), TaxiStatus.OCCUPIED);
    } catch (IOException e) {
        LOGGER.error("Error while updating taxi status", e);
    }
}
 
Example #30
Source File: RedisIndexedSessionRepository.java    From spring-session with Apache License 2.0 4 votes vote down vote up
@Override
public void onMessage(Message message, byte[] pattern) {
	byte[] messageChannel = message.getChannel();
	byte[] messageBody = message.getBody();

	String channel = new String(messageChannel);

	if (channel.startsWith(this.sessionCreatedChannelPrefix)) {
		// TODO: is this thread safe?
		@SuppressWarnings("unchecked")
		Map<Object, Object> loaded = (Map<Object, Object>) this.defaultSerializer.deserialize(message.getBody());
		handleCreated(loaded, channel);
		return;
	}

	String body = new String(messageBody);
	if (!body.startsWith(getExpiredKeyPrefix())) {
		return;
	}

	boolean isDeleted = channel.equals(this.sessionDeletedChannel);
	if (isDeleted || channel.equals(this.sessionExpiredChannel)) {
		int beginIndex = body.lastIndexOf(":") + 1;
		int endIndex = body.length();
		String sessionId = body.substring(beginIndex, endIndex);

		RedisSession session = getSession(sessionId, true);

		if (session == null) {
			logger.warn("Unable to publish SessionDestroyedEvent for session " + sessionId);
			return;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("Publishing SessionDestroyedEvent for session " + sessionId);
		}

		cleanupPrincipalIndex(session);

		if (isDeleted) {
			handleDeleted(session);
		}
		else {
			handleExpired(session);
		}
	}
}