使用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)机制, 若对象无法响应某个选择子,则进入消息转发流程. ...
随机推荐
- 在搭建tesseract-OCR环境中遇到问题和反省
Tesseract,一款由HP实验室开发由Google维护的开源OCR(Optical Character Recognition , 光学字符识别)引擎,特点是开源,免费,支持多语言,多平台. 在搭 ...
- Github上如何查看当前最流行的开源项目
先声明下:只针对初学者,大神的话勿喷. 针对题标的这个问题,按照如下步骤操作即可: 进入Github网站后,显示的页面如下所示: 点击"Explore"链接,进入如下页面: 页面上 ...
- web渗透 学习计划(转载)
作者:向生李链接:https://www.zhihu.com/question/21914899/answer/39344435来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...
- MySQL 数据库的创建&修改
-- 创建数据库 CREATE DATABASE [IF NOT EXISTS]<数据库名> DEFAULT CHARACTER SET utf8; -- 默认字符集为utf8 -- 指定 ...
- HTML,CSS---问题记录
1,,登录框input和标签垂直方向对不齐,咋解决? 给input框外套一层span标签,给span标签设置宽高,让它和左边或右边的标签对齐. 不要直接给input设置宽高,这样是对不齐的 2,套没有 ...
- 【Python 11】汇率兑换4.0(函数)
1.案例描述 设计一个汇率换算程序,其功能是将美元换算成人民币,或者相反. 2.0增加功能:根据输入判断是人民币还是美元,进行相应的转换计算 3.0增加功能:程序可以一直运行,知道用户选择退出 4.0 ...
- ORACLE跨数据库查询的方法
原文地址:http://blog.csdn.net/huzhenwei/article/details/2533869 本文简述了通过创建database link实现Oracle跨数据库查询的方法 ...
- CentOS 7 安装Kubernetes(单机版)
一.关闭CentOS自带的防火墙服务 # systemctl disable firewalld # systemctl stop firewalld 二.安装etcd和Kubernetes软件( ...
- golang 解析XML
用adb操控android手机时,可以解析页面控件信息(xml) 代码如下: package main import ( "encoding/xml" "fmt" ...
- 文本分类实战(五)—— Bi-LSTM + Attention模型
1 大纲概述 文本分类这个系列将会有十篇左右,包括基于word2vec预训练的文本分类,与及基于最新的预训练模型(ELMo,BERT等)的文本分类.总共有以下系列: word2vec预训练词向量 te ...