使用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)机制, 若对象无法响应某个选择子,则进入消息转发流程. ...
随机推荐
- SQLServer之创建INSTEAD OF INSERT,UPDATE,DELETE触发器
INSTEAD OF触发器工作原理 INSTEAD OF表示并不执行其所定义的操作INSERT,UPDATE ,DELETE,而仅是执行触发器本身,即当对表进行INSERT.UPDATE 或 DELE ...
- Loj #2324. 「清华集训 2017」小 Y 和二叉树
Loj #2324. 「清华集训 2017」小 Y 和二叉树 小Y是一个心灵手巧的OIer,她有许多二叉树模型. 小Y的二叉树模型中,每个结点都具有一个编号,小Y把她最喜欢的一个二叉树模型挂在了墙上, ...
- MYSQL中文乱码以及character_set_database属性修改
新安装MYSQL,还没有修改数据库系统编码. 之后由于创建数据库时候:create database db_name; 没有指定编码,之后发现乱码就修改各个属性之后还是乱码,便开始配置数据库属性,之后 ...
- zabbix优化,配合文件,zabbix_get命令
一.配置文件优化 server端配置文件添加如下 StartPollers=160 #zabbix_server的进程数 StartPollersUnreacheable=80 #默认情况下,ZABB ...
- 两台主机,ssh端口不同,如何拷贝文件
A主机ip:172.26.225.199 ssh端口12995 B主机ip:172.26.225.200 ssh端口12991 将B主机的文件拷贝到A主机 [root@test2019030517 s ...
- Web前端知识点记录
一.HTML的加载顺序 浏览器边下载HTML,边解析HTML代码,二者是从上往下同步进行的 先解析<head>中的代码,在<head>中遇到了<script>标签, ...
- Filebeat配置参考手册
Filebeat的配置参考 指定要运行的模块 前提: 在运行Filebeat模块之前,需要安装并配置Elastic堆栈: 安装Ingest Node GeoIP和User Agent插件.这些插件需要 ...
- sass的使用
1.声明变量-全局声明-局部声明 中划线或下划线两种用法相互兼容 $nav-color: #F90; $highlight-border: 1px solid $nav-color; nav{ $ ...
- 646. Maximum Length of Pair Chain(medium)
You are given n pairs of numbers. In every pair, the first number is always smaller than the second ...
- Zookeeper 客户端命令