(十七) 整合spring cloud云架构 -消息驱动 Spring Cloud Stream

在使用spring cloud云架构的时候,我们不得不使用Spring cloud Stream,因为消息中间件的使用在项目中无处不在,我们公司后面做了娱乐方面的APP,在使用spring cloud做架构的时候,其中消息的异步通知,业务的异步处理都需要使用消息中间件机制。spring cloud的官方给出的集成建议(使用rabbit mq和kafka),我看了一下源码和配置,只要把rabbit mq集成,kafka只是换了一个pom配置jar包而已,闲话少说,我们就直接进入配置实施:

1. 简介:

Spring cloud Stream 数据流操作开发包,封装了与Redis,Rabbit、Kafka等发送接收消息。

2. 使用工具:

rabbit,具体的下载和安装细节我这里不做太多讲解,网上的实例太多了

3. 创建commonservice-mq-producer消息的发送者项目,在pom里面配置stream-rabbit的依赖

<span style="font-size: 16px;"><!-- 引入MQ消息驱动的微服务包,引入stream只需要进行配置化即可,是对rabbit、kafka很好的封装 -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency></span>
复制代码

 4. 在yml文件里面配置rabbit mq

<span style="font-size: 16px;">server:
  port: 5666
spring:
  application:
    name: commonservice-mq-producer
  profiles: 
    active: dev
  cloud:
    config:
      discovery: 
        enabled: true
        service-id: commonservice-config-server
  <span style="color: #ff0000;"># rabbitmq和kafka都有相关配置的默认值,如果修改,可以再次进行配置
    stream:
      bindings:
        mqScoreOutput: 
          destination: honghu_exchange
          contentType: application/json
          
  rabbitmq:
     host: localhost
     port: 5672
     username: honghu
     password: honghu</span>
eureka: 
  client:
    service-url:
      defaultZone: http://honghu:123456@localhost:8761/eureka
  instance:
    prefer-ip-address: true</span>
复制代码

 5. 定义接口ProducerService

<span style="font-size: 16px;">package com.honghu.cloud.producer;

import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.SubscribableChannel;

public interface ProducerService {
	
	String SCORE_OUPUT = "mqScoreOutput";
	
	@Output(ProducerService.SCORE_OUPUT)
	SubscribableChannel sendMessage();
}</span>
复制代码

 6. 定义绑定

<span style="font-size: 16px;">package com.honghu.cloud.producer;

import org.springframework.cloud.stream.annotation.EnableBinding;

@EnableBinding(ProducerService.class)
public class SendServerConfig {

}</span>
复制代码

 7. 定义发送消息业务ProducerController

<span style="font-size: 16px;">package com.honghu.cloud.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.honghu.cloud.common.code.ResponseCode;
import com.honghu.cloud.common.code.ResponseVO;
import com.honghu.cloud.entity.User;
import com.honghu.cloud.producer.ProducerService;
import net.sf.json.JSONObject
@RestController
@RequestMapping(value = "producer")
public class ProducerController {
	
	@Autowired
	private ProducerService producerService;
	/**
	 * 通过get方式发送</span>对象<span style="font-size: 16px;">
	 * @param name 路径参数
	 * @return 成功|失败
	 */
	@RequestMapping(value = "/sendObj", method = RequestMethod.GET)
	public ResponseVO sendObj() {
		User user = new User(1, "hello User");
		<span style="color: #ff0000;">Message<User> msg = MessageBuilder.withPayload(user).build();</span>
		boolean result = producerService.sendMessage().send(msg);
		if(result){
			return ResponseCode.buildEnumResponseVO(ResponseCode.RESPONSE_CODE_SUCCESS, false);
		}
		return ResponseCode.buildEnumResponseVO(ResponseCode.RESPONSE_CODE_FAILURE, false);
	}
	/**
	 * 通过get方式发送字符串消息
	 * @param name 路径参数
	 * @return 成功|失败
	 */
	@RequestMapping(value = "/send/{name}", method = RequestMethod.GET)
	public ResponseVO send(@PathVariable(value = "name", required = true) String name) {
		Message msg = MessageBuilder.withPayload(name.getBytes()).build();
		boolean result = producerService.sendMessage().send(msg);
		if(result){
			return ResponseCode.buildEnumResponseVO(ResponseCode.RESPONSE_CODE_SUCCESS, false);
		}
		return ResponseCode.buildEnumResponseVO(ResponseCode.RESPONSE_CODE_FAILURE, false);
	}
	/**
	 * 通过post方式发送</span>json对象<span style="font-size: 16px;">
	 * @param name 路径参数
	 * @return 成功|失败
	 */
	@RequestMapping(value = "/sendJsonObj", method = RequestMethod.POST)
	public ResponseVO sendJsonObj(@RequestBody JSONObject jsonObj) {
		Message<JSONObject> msg = MessageBuilder.withPayload(jsonObj).build();
		boolean result = producerService.sendMessage().send(msg);
		if(result){
			return ResponseCode.buildEnumResponseVO(ResponseCode.RESPONSE_CODE_SUCCESS, false);
		}
		return ResponseCode.buildEnumResponseVO(ResponseCode.RESPONSE_CODE_FAILURE, false);
	}
}
</span>
复制代码

8. 创建commonservice-mq-consumer1消息的消费者项目,在pom里面配置stream-rabbit的依赖

<!-- 引入MQ消息驱动的微服务包,引入stream只需要进行配置化即可,是对rabbit、kafka很好的封装 -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
复制代码

9. 在yml文件中配置:

server:
  port: 5111
spring:
  application:
    name: commonservice-mq-consumer1
  profiles: 
    active: dev
  cloud:
    config:
      discovery: 
        enabled: true
        service-id: commonservice-config-server
        
    <span style="color: #ff0000;">stream:
      bindings:
        mqScoreInput:
          group: honghu_queue
          destination: honghu_exchange
          contentType: application/json
          
  rabbitmq:
     host: localhost
     port: 5672
     username: honghu
     password: honghu</span>
eureka: 
  client:
    service-url:
      defaultZone: http://honghu:123456@localhost:8761/eureka
  instance:
    prefer-ip-address: true
复制代码

10. 定义接口ConsumerService

package com.honghu.cloud.consumer;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.messaging.SubscribableChannel;
public interface ConsumerService {
	<span style="color: #ff0000;">String SCORE_INPUT = "mqScoreInput";
	@Input(ConsumerService.SCORE_INPUT)
	SubscribableChannel sendMessage();</span>

}
复制代码

11. 定义启动类和消息消费

package com.honghu.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import com.honghu.cloud.consumer.ConsumerService;
import com.honghu.cloud.entity.User;
@EnableEurekaClient
@SpringBootApplication
@EnableBinding(ConsumerService.class) //可以绑定多个接口
public class ConsumerApplication {
	public static void main(String[] args) {
		SpringApplication.run(ConsumerApplication.class, args);
	}
	<span style="color: #ff0000;">@StreamListener(ConsumerService.SCORE_INPUT)
	public void onMessage(Object obj) {
		System.out.println("消费者1,接收到的消息:" + obj);
	}</span>

}
复制代码

12. 分别启动commonservice-mq-producer、commonservice-mq-consumer1

13. 通过postman来验证消息的发送和接收













可以看到接收到了消息,下一章我们介绍mq的集群方案。

到此,整个消息中心方案集成完毕 完整项目的源码来源 技术支持1791743380

欢迎大家和我一起学习spring cloud构建微服务云架构,我这边会将近期研发的spring cloud微服务云架构的搭建过程和精髓记录下来,帮助更多有兴趣研发spring cloud框架的朋友,大家来一起探讨spring cloud架构的搭建过程及如何运用于企业项目。


转载于:https://juejin.im/post/5b90f6b65188255c9c750c28

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当前课程中商城项目的实战码是我发布在 GitHub 上的开项目 newbee-mall (新蜂商城),目前已有 9900 多个 Star,本课程是一个 Spring Boot 技术栈的实战类课程,课程共分为 3 大部分,前面两个部分为基础环境准备和相关概念介绍,第三个部分是 Spring Boot 商城项目功能的讲解,让大家实际操作并实践上手一个大型的线上商城项目,并学习到一定的开发经验以及其中的开发技巧。商城项目所涉及的功能结构图整理如下: 作者寄语本课程录制于2019年,距今已有一段时间。期间,Spring Boot技术栈也有一些版本升级,比如Spring Boot 2.7.x发版、Spring Boot 3.x版本正式版本。对于这些情况,笔者会在本课程实战项目的开仓库中创建不同的代码分支,保持实战项目的码更新,保证读者朋友们不会学习过气的知识点。新蜂商城的优化和迭代工作不会停止,不仅仅是功能的优化,在技术栈上也会不断的增加,截止2023年,新蜂商城已经发布了 7 个重要的版本,版本记录及开发计划如下图所示。 课程特色 对新手开发者十分友好,无需复杂的操作步骤,仅需 2 秒就可以启动这个完整的商城项目最终的实战项目是一个企业级别的 Spring Boot 大型项目,对于各个阶段的 Java 开发者都是极佳的选择实践项目页面美观且实用,交互效果完美教程详细开发教程详细完整、文档资齐全代码+讲解+演示网站全方位保证,向 Hello World 教程说拜拜技术栈新颖且知识点丰富,学习后可以提升大家对于知识的理解和掌握,可以进一步提升你的市场竞争力 课程预览 以下为商城项目的页面和功能展示,分别为:商城首页 1商城首页 2购物车订单结算订单列表支付页面后台管理系统登录页商品管理商品编辑

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值