使用Spring-Integration实现http消息转发
目标:接收来自华为云的服务器报警信息,并转发到钉钉的自定义机器人中
使用Spring-Integration不仅节省了很多配置,还增加了可用性。
更多关于Spring-Integration的介绍可参照官网:http://spring.io/projects/spring-integration。
样例已上传至Github:https://github.com/hackyoMa/spring-integration-http-demo
项目基于Spring Boot2.0。
依赖:
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-http</artifactId>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>jackson-module-kotlin</artifactId>
<groupId>com.fasterxml.jackson.module</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
配置文件application.properties:
server.port=8080
receive.path=/receiveGateway
forward.path=https://oapi.dingtalk.com/robot/send?access_token=xxx
主类:
package com.integration.http; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource; @SpringBootApplication
@ImportResource(locations = "classpath:http-inbound-config.xml")
public class HttpApplication { public static void main(String[] args) {
SpringApplication.run(HttpApplication.class, args);
} }
接收配置http-inbound-config.xml(放置resources目录):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-http="http://www.springframework.org/schema/integration/http"
xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/http http://www.springframework.org/schema/integration/http/spring-integration-http.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:config/application.properties"/> <bean id="serviceActivator" class="com.integration.http.ServiceActivator">
</bean> <int-http:inbound-gateway request-channel="receiveChannel" path="${receive.path}" supported-methods="POST">
<int-http:cross-origin/>
</int-http:inbound-gateway> <int:channel id="receiveChannel"/> <int:chain input-channel="receiveChannel">
<int:service-activator ref="serviceActivator"/>
</int:chain> </beans>
发送配置http-outbound-config.xml(放置resources目录):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-http="http://www.springframework.org/schema/integration/http"
xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/http http://www.springframework.org/schema/integration/http/spring-integration-http.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:config/application.properties"/> <int:gateway id="requestGateway"
service-interface="com.integration.http.RequestGateway"
default-request-channel="requestChannel"/> <int:channel id="requestChannel"/> <int-http:outbound-gateway request-channel="requestChannel"
url="${forward.path}"
http-method="POST"
expected-response-type="java.lang.String"
charset="UTF-8"/> </beans>
激活器(对转发信息过滤和修改)
ServiceActivator.java:
package com.integration.http; import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.support.GenericMessage; import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date; public class ServiceActivator implements MessageHandler { private final static Log logger = LogFactory.getLog(ServiceActivator.class);
private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private JSONObject formatNotificationMsg(JSONObject payload) {
String subject = payload.getString("subject");
String content = payload.getString("message");
long sendTime = Long.parseLong(payload.getString("timestamp"));
JSONObject params = new JSONObject();
params.put("msgtype", "markdown");
JSONObject message = new JSONObject();
message.put("title", subject);
message.put("text", "# 通知-" + subject + " \n**" + content + "** \n*" + SDF.format(new Date(sendTime)) + "*");
params.put("markdown", message);
return params;
} private JSONObject formatSubscriptionConfirmationMsg(JSONObject payload) {
String type = payload.getString("type");
String subject;
String content;
if ("SubscriptionConfirmation".equals(type)) {
subject = "确认订阅";
content = "确认订阅请点击此处";
} else {
subject = "取消订阅成功";
content = "再次订阅请点击此处";
}
String subscribeUrl = payload.getString("subscribe_url");
long sendTime = Long.parseLong(payload.getString("timestamp"));
JSONObject params = new JSONObject();
params.put("msgtype", "markdown");
JSONObject message = new JSONObject();
message.put("title", subject);
message.put("text", "# 通知-" + subject + "\n**[" + content + "](" + subscribeUrl + ")**\n*" + SDF.format(new Date(sendTime)) + "*");
params.put("markdown", message);
return params;
} @Override
public void handleMessage(Message<?> message) throws MessagingException {
try {
JSONObject payload = JSONObject.parseObject(new String((byte[]) message.getPayload(), "UTF-8"), JSONObject.class);
logger.info("接收参数:" + payload.toJSONString());
String type = payload.getString("type");
if ("Notification".equals(type)) {
payload = formatNotificationMsg(payload);
logger.info("发送参数:" + payload.toJSONString());
Message<?> toSend = new GenericMessage<>(payload.toJSONString(), message.getHeaders());
activator(toSend);
} else if ("SubscriptionConfirmation".equals(type) || "UnsubscribeConfirmation".equals(type)) {
payload = formatSubscriptionConfirmationMsg(payload);
logger.info("发送参数:" + payload.toJSONString());
Message<?> toSend = new GenericMessage<>(payload.toJSONString(), message.getHeaders());
activator(toSend);
} else {
logger.info("不支持的消息类型:" + type);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} private void activator(Message<?> message) {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("http-outbound-config.xml");
RequestGateway requestGateway = context.getBean("requestGateway", RequestGateway.class);
String reply = requestGateway.echo(message);
logger.info("发送回执:" + reply);
context.close();
} }
请求网关(发送请求):
RequestGateway.java:
package com.integration.http;
import org.springframework.messaging.Message;
public interface RequestGateway {
String echo(Message<?> message);
}
这样就能将配置文件中接收地址传来的参数转发到转发地址中去。
使用Spring-Integration实现http消息转发的更多相关文章
- Spring Integration概述
1. Spring Integration概述 1.1 背景 Spring框架的一个重要主题是控制反转.从广义上来说,Spring处理其上下文中管理的组件的职责.只要组件减轻了职责,它们同 ...
- [转] Spring Integration 系统集成
[From] http://blog.csdn.net/w_x_z_/article/details/53316618 pring Ingegration 提供了基于Spring的EIP(Enterp ...
- [置顶]
spring集成mina 实现消息推送以及转发
spring集成mina: 在学习mina这块时,在网上找了很多资料,只有一些demo,只能实现客户端向服务端发送消息.建立长连接之类.但是实际上在项目中,并不简单实现这些,还有业务逻辑之类的处理以及 ...
- spring Integration服务总线
最新项目中使用数据交换平台,主要通过交换平台抓取HIS数据库医生医嘱检查检验等数据以及FTP上的txt文件,html等病程文件,生成XML文件,之后通过业务系统按业务规则对数据进行处理,再将其存入数据 ...
- 几种常见的微服务架构方案简述——ZeroC IceGrid、Spring Cloud、基于消息队列
微服务架构是当前很热门的一个概念,它不是凭空产生的,是技术发展的必然结果.虽然微服务架构没有公认的技术标准和规范草案,但业界已经有一些很有影响力的开源微服务架构平台,架构师可以根据公司的技术实力并结合 ...
- 几种常见的微服务架构方案——ZeroC IceGrid、Spring Cloud、基于消息队列、Docker Swarm
微服务架构是当前很热门的一个概念,它不是凭空产生的,是技术发展的必然结果.虽然微服务架构没有公认的技术标准和规范草案,但业界已经有一些很有影响力的开源微服务架构平台,架构师可以根据公司的技术实力并结合 ...
- iOS - 消息转发处理
详细运行时基础 NSInvocation介绍 NSHipster-Swizzling Objective-C Method相关方法分析 Type Encodings Objc是OOP,所以有多态. 当 ...
- iOS 消息转发机制
这篇博客的前置知识点是 OC 的消息传递机制,如果你对此还不了解,请先学习之,再来看这篇.这篇博客我尝试用口语的方式像讲述 PPT 一样给大家讲述这个知识点. 我们来思考一个问题,如果对象在收到无法解 ...
- ios 消息转发初探
有时候服务器的接口文档上一个数据写的是string类型,这时候你就会直接把它赋值给一个label. 问题来了,有时候这个string的确是string,没有问题,有时候又是NSNumber,当然不管三 ...
- Effective Objective-C 2.0 — 第12条:理解消息转发机制
11 条讲解了对象的消息传递机制 12条讲解对象在收到无法解读的消息之后会发生什么,就会启动“消息转发”(message forwarding)机制, 若对象无法响应某个选择子,则进入消息转发流程. ...
随机推荐
- Bootstrap -- 插件: 模态框、滚动监听、标签页
Bootstrap -- 插件: 模态框.滚动监听.标签页 1. 模态框(Modal): 覆盖在父窗体上的子窗体. 使用模态框: <!DOCTYPE html> <html> ...
- 一篇文章教你如何用 Python 记录日志
前言: 这篇文章是我copy别人的,但是个人认为讲的真的很细致,有原理有实例,不仅仅只教你如何使用日志更会叫你知道日志的原理,真的非常棒,虽然文章很长,也许你不会认认真真读完, 但是当你遇到问题时这篇 ...
- Docker的使用初探(二):Docker与.NET Core的结合
目录 Docker的使用初探(二):Docker与.NET Core的结合 添加Dockefile 1. 在创建项目时添加 2. 手动添加 3. 容器业务流程协调控制程序支持 Dockefile语法 ...
- gulp结合Thinkphp配置
gulpfile.js文件 /*! * gulp * $ npm install gulp gulp-ruby-sass gulp-cached gulp-uglify gulp-rename gul ...
- 【题解】P1171 售货员的难题
Tags 搜索,状压. 裸的旅行商问题 #include <stdio.h> #include <string.h> #define re register #define ...
- ESP8266天线问题
http://www.icxbk.com/ask/detail/28832.html 目前市面上常见的外接天线包括 1.FPC天线,就是一小块柔性PCB,上面走一个铜线,下方不覆铜,然后一般带一个贴纸 ...
- sigsuspend()阻塞:异步信号SIGIO为什么会被截胡?
关键词:fcntl.fasync.signal.sigsuspend.pthread_sigmask.trace events. 此文主要是解决问题过程中的记录,内容有较多冗余.但也反映解决问题中用到 ...
- ubuntu安装docker{ubuntu16.04下安装docker}
一.开始安装 第一步: 由于apt官方库里的docker版本可能比较旧,所以先卸载可能存在的旧版本: $ sudo apt-get remove docker docker-engine d ...
- iOS开发基础-图片切换(2)之懒加载
延续:iOS开发基础-图片切换(1),对(1)里面的代码进行改善. 在 ViewController 类中添加新的数组属性: @property (nonatomic, strong) NSArra ...
- 基于 WebGL 的 HTML5 楼宇自控 3D 可视化监控
前言 智慧楼宇和人们的生活息息相关,楼宇智能化程度的提高,会极大程度的改善人们的生活品质,在当前工业互联网大背景下受到很大关注.目前智慧楼宇可视化监控的主要优点包括: 智慧化 -- 智慧楼宇是一个生态 ...