构建一个简单的spring-boot项目messaging with redis

目标

构建一个简单的spring-boot项目,发送消息给Redis,从Redis接收消息;

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo_redis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo_redis</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>
消息接收处理:
  • Receiver是一个一般的简易Java对象;
  • Receiver需要被封装到实现了MessageListener接口的MessageLIstenerAdapter对象中才能接收和处理数据
package com.example.demo_redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class Receiver {
    private static final Logger logger = LoggerFactory.getLogger(Receiver.class);
    private AtomicInteger counter = new AtomicInteger();
    public void receiveMessage(String message){
        logger.info("Received <"+message+">");
        counter.incrementAndGet();
    }
    public int getCount(){
        return counter.get();
    }
}
启动
  • 启动
    • 启动spring应用上下文;应用上下文会启动message listener容器Bean;message listener容器Bean启动监听消息;
    • 从spring上下文获取StringRedisTemplate Bean,用它来发送消息,消息主体是chat;
    • while阻塞主进程,一直发送和等待接收,无论发送多少条消息,只要接收到一条即会终止;
  • Bean: RedisMessageListenerContainer
    • messageListenerAdapter: 在消息监听容器中被注册为消息监听器,用于监听名为chat的消息主体;
    • 连接工厂redisConnectionFactory和消息监听容器Bean都是用来监听消息的;
  • Bean: MessageListenerAdapter
    • 封装消息处理对象,配置消息处理方法
  • Bean: StringRedisTemplate
    • 要发送Redis消息,需要使用RedisTemplate的实现类
    • StringRedisTemplate是RedisTemplate的实现类,主要关注Redis的通用用法,对应的key和value都是String
package com.example.demo_redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@SpringBootApplication
public class DemoRedisApplication {
	private static final Logger logger = LoggerFactory.getLogger(DemoRedisApplication.class);
	public static void main(String[] args) throws InterruptedException {
		ApplicationContext ctx = SpringApplication.run(DemoRedisApplication.class, args);
		StringRedisTemplate stringRedisTemplate = ctx.getBean(StringRedisTemplate.class);
		Receiver receiver = ctx.getBean(Receiver.class);
		while(receiver.getCount() == 0){
			logger.info("Sending message...");
			stringRedisTemplate.convertAndSend("chat", "Hello redis!");
			Thread.sleep(500L);
		}
		System.exit(0);
	}
	@Bean
	RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory, MessageListenerAdapter messageListenerAdapter){
		RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);	redisMessageListenerContainer.addMessageListener(messageListenerAdapter,new PatternTopic("chat"));
		return  redisMessageListenerContainer;
	}
	@Bean
	MessageListenerAdapter listenerAdapter(Receiver receiver){
		return new MessageListenerAdapter(receiver, "receiveMessage");
	}
	@Bean
	Receiver receiver(){
		return new Receiver();
	}
	@Bean
	StringRedisTemplate template(RedisConnectionFactory redisConnectionFactory){
		return new StringRedisTemplate(redisConnectionFactory);
	}
}
application.properties
spring.redis.host=192.168.2.132
spring.redis.port=6379
spring.redis.password=redispwd
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot Messaging: Messaging APIs for Enterprise and Integration Solutions by Felipe Gutierrez English | 5 Jun. 2017 | ISBN: 1484212258 | 196 Pages | PDF | 6.36 MB Build messaging applications using the power of Spring Boot; use Spring application events over the Web; use WebSocket, SockJS, and STOMP messaging with Spring MVC; and use Spring JMS, Redis Pub/Sub and Spring AMQP for reliable messaging solutions. This book covers all the Spring Messaging APIs using Spring Boot. Written by a Pivotal engineer, Spring Boot Messaging is an authoritative guide to the many messaging APIs and how to use these for creating enterprise and integration solutions. You will learn and integrate these messaging APIs with more complex enterprise and cloud applications: for example, you will see how to use Spring Cloud Stream for creating message-driven and cloud native microservices. In addition, you’ll discover the new Spring Integration DSL and use it with Spring Cloud Stream to build integration solutions using every enterprise integration pattern. Finally, you’ll see Spring Reactor and Spring Cloud to take your application to the next level. After reading this book, you will come away with a case study application walk-through and will be able to use it as a template for building your own Spring messaging applications or messaging features within your enterprise or cloud application. What You'll Learn Use the main Spring messaging APIs with Spring Framework 5 Build messaging applications over the Web Use WebSocket, SockJS, and STOMP messaging Integrate Spring JMS and Spring AMQP into your applications Work with Spring Cloud Stream and microservices Who This Book Is For Enterprise Java developers who have at least some previous experience with the Spring Framework and/or the Spring platform.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值