(14)java版spring cloud+spring boot+redisソーシャル電子商取引プラットフォーム-springbootでredisでメッセージキューを実現...

3404 ワード

電子商取引の社交のプラットフォームのソースコードはペンギンをプラスして求めます:一零三八七四六二六
準備フェーズ
  • java 1.8
  • maven 3.0
  • idea

  • 環境依存
    新しいspringbootプロジェクトを作成し、pomファイルにspring-boot-starter-data-redis依存性を追加します.
    
                org.springframework.boot
                spring-boot-starter-data-redis
            

    メッセージ受信者の作成
    通常のクラスでspringbootに注入する必要があるREcevierクラス.
    public class Receiver {
        private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);
    
        private CountDownLatch latch;
    
        @Autowired
        public Receiver(CountDownLatch latch) {
            this.latch = latch;
        }
    
        public void receiveMessage(String message) {
            LOGGER.info("Received  + message + ">");
            latch.countDown();
        }
    }

    メッセージ受信者への注入
    @Bean
        Receiver receiver(CountDownLatch latch) {
            return new Receiver(latch);
        }
    
        @Bean
        CountDownLatch latch() {
            return new CountDownLatch(1);
        }
    
        @Bean
        StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
            return new StringRedisTemplate(connectionFactory);
        }

    メッセージリスナーコンテナの注入
    Spring data redisでは、redisを使用してメッセージを送信し、メッセージを受信するには、3つのものが必要です.
  • 接続工場
  • メッセージ傍受容器
  • Redis template

  • 上記の1、3ステップは既に完了しているので、メッセージリスニングコンテナを注入するだけでよい.
    @Bean
        RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                MessageListenerAdapter listenerAdapter) {
    
            RedisMessageListenerContainer container = new RedisMessageListenerContainer();
            container.setConnectionFactory(connectionFactory);
            container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
    
            return container;
        }
    
        @Bean
        MessageListenerAdapter listenerAdapter(Receiver receiver) {
            return new MessageListenerAdapter(receiver, "receiveMessage");
        }

    テスト
    スプリングbootエントリでのmainメソッド:
    public static void main(String[] args) throws Exception{
            ApplicationContext ctx =  SpringApplication.run(SpringbootRedisApplication.class, args);
    
            StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
            CountDownLatch latch = ctx.getBean(CountDownLatch.class);
    
            LOGGER.info("Sending message...");
            template.convertAndSend("chat", "Hello from Redis!");
    
            latch.await();
    
            System.exit(0);
        }

    Spring Cloud大手企業分布式マイクロサービスクラウド構築B 2 B 2 C電子商取引プラットフォームソースコードペンギンを追加してください:一零三八七四六二六
    転載先:https://juejin.im/post/5cde715de51d4510be453ee1