redisメッセージパブリケーションサブスクリプションとメッセージキュー

11570 ワード

redisはメッセージのパブリケーションサブスクリプションを実現し、javaでのサブスクリプションパブリケーションモードとして使用できます.
純粋なredisのパブリケーションサブスクリプションredisクライアント1では、コマンドSUBSCRIBE talkを使用してチャネルtalk上のメッセージredisクライアント2にも同様にこのコマンドを実行してチャネルtalk redisクライアント3にサブスクリプションするコマンドPUBLISH talk 'test'を使用して、クライアント1と2が同時にメッセージを受信していることを発見することができる
JAvaインプリメンテーションはspring-redisの中のredisTemplateツールによって実現することができる.メッセージの発行
/**
 * redis    
 *
 * @param channel
 * @param message
 */
public void sendMessage(String channel, String message) {
    redisTemplate.convertAndSend(channel, message);
}

convertAndSendメソッドを直接使用すると、指定したチャネルにメッセージをパブリッシュできます.
2.メッセージ傍受メッセージを傍受するには2つのステップが必要であり、メッセージ傍受クラスがxmlに登録されているこのクラスの傍受クラスには2つの実装方式がある.1つは実装orgである.springframework.data.redis.connection.MessageListenerインタフェース、onMessageを実装する方法の例コードは以下の通りです.
@Component
public class RedisMessageListener implements MessageListener {

    @Autowired
    private RedisTemplate redisTemplate;

    private static Logger logger = Logger.getLogger(RedisMessageListener.class);

    @Override
    public void onMessage(Message message, byte[] pattern) {
        byte[] body = message.getBody();//    valueSerializer
        byte[] channel = message.getChannel();
        //        ,   key,value        string。
        //   key   stringSerializer。 redisTemplate.convertAndSend  
        String msgContent = (String) redisTemplate.getValueSerializer().deserialize(body);
        String topic = (String) redisTemplate.getStringSerializer().deserialize(channel);
        logger.info("redis--topic:" + topic + "  body:" + msgContent);
    }
}

独自に定義したクラス、メソッド名を使用して独自に定義することもできます.例は次のとおりです.
@Component
public class EventListener {

    private static Logger logger = Logger.getLogger(EventListener.class);

    public void getMessage(String message, String channel) {
        logger.info(message);
    }
} 

この2つの方法の違いは、リスナーを登録するときの構成が少し異なるredisプロファイルであることです.

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:redis="http://www.springframework.org/schema/redis"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd                           http://www.springframework.org/schema/redis http://www.springframework.org/schema/redis/spring-redis-1.0.xsd">

<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <property name="maxIdle" value="${redis.maxIdle}" />
    
    <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
    <property name="testOnBorrow" value="${redis.testOnBorrow}" />
bean>

<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
      p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"
      p:pool-config-ref="poolConfig"/>

<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
    <property name="connectionFactory" ref="redisConnectionFactory"/>
bean>

<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>

<redis:listener-container>
    <redis:listener ref="redisMessageListener" topic="talk"/>
    <redis:listener ref="eventListener" topic="talk*" method="getMessage"
                    serializer="stringRedisSerializer">redis:listener>
redis:listener-container>
beans>

redisメッセージキューredisメッセージキューredisのlistデータ構造を使用して実装(左から右へ)
/**
 *             
 *
 * @param key
 * @param value
 * @return
 */
public void leftPush(String key, String value) {
    redisTemplate.opsForList().leftPush(key, value);
}

このコードは指定したリストの左側に値を挿入します.
/**
 *            (      ,         )
 *
 * @param key
 * @param timeout
 * @param unit
 * @return
 */
public String rightPop(String key, long timeout, TimeUnit unit) {
    return redisTemplate.opsForList().rightPop(key, timeout, unit);
}

以上のコードは、指定したリストの右側からデータをポップアップできます(ない場合は、指定した時間が空に戻るのを待つことになります).このメソッドを使用して、プロジェクトでスレッドを起動するだけで、メッセージキューのリスニングを実現できます.
@PostConstruct
public void messageListener() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                rightPop(....)
                ....
            }
        }
    }, "        ").start();
}

ポップアップ・メソッドでは、
/**
 *         ,           (          ,       )
 *
 * @param sourceKey
 * @param destinationKey
 * @param timeout
 * @param unit
 * @return
 */
public String rightPopAndLeftPush(String sourceKey, String destinationKey, long timeout, TimeUnit unit) {
    return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey, timeout, unit);
    }

この方法はコードを最適化し,ポップアップを実現しながら処理キュー(トランザクション)を挿入する.