目标:接收来自华为云的服务器报警信息,并转发到钉钉的自定义机器人中

使用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消息转发的更多相关文章

  1. Spring Integration概述

    1.   Spring Integration概述 1.1     背景 Spring框架的一个重要主题是控制反转.从广义上来说,Spring处理其上下文中管理的组件的职责.只要组件减轻了职责,它们同 ...

  2. [转] Spring Integration 系统集成

    [From] http://blog.csdn.net/w_x_z_/article/details/53316618 pring Ingegration 提供了基于Spring的EIP(Enterp ...

  3. [置顶] spring集成mina 实现消息推送以及转发

    spring集成mina: 在学习mina这块时,在网上找了很多资料,只有一些demo,只能实现客户端向服务端发送消息.建立长连接之类.但是实际上在项目中,并不简单实现这些,还有业务逻辑之类的处理以及 ...

  4. spring Integration服务总线

    最新项目中使用数据交换平台,主要通过交换平台抓取HIS数据库医生医嘱检查检验等数据以及FTP上的txt文件,html等病程文件,生成XML文件,之后通过业务系统按业务规则对数据进行处理,再将其存入数据 ...

  5. 几种常见的微服务架构方案简述——ZeroC IceGrid、Spring Cloud、基于消息队列

    微服务架构是当前很热门的一个概念,它不是凭空产生的,是技术发展的必然结果.虽然微服务架构没有公认的技术标准和规范草案,但业界已经有一些很有影响力的开源微服务架构平台,架构师可以根据公司的技术实力并结合 ...

  6. 几种常见的微服务架构方案——ZeroC IceGrid、Spring Cloud、基于消息队列、Docker Swarm

    微服务架构是当前很热门的一个概念,它不是凭空产生的,是技术发展的必然结果.虽然微服务架构没有公认的技术标准和规范草案,但业界已经有一些很有影响力的开源微服务架构平台,架构师可以根据公司的技术实力并结合 ...

  7. iOS - 消息转发处理

    详细运行时基础 NSInvocation介绍 NSHipster-Swizzling Objective-C Method相关方法分析 Type Encodings Objc是OOP,所以有多态. 当 ...

  8. iOS 消息转发机制

    这篇博客的前置知识点是 OC 的消息传递机制,如果你对此还不了解,请先学习之,再来看这篇.这篇博客我尝试用口语的方式像讲述 PPT 一样给大家讲述这个知识点. 我们来思考一个问题,如果对象在收到无法解 ...

  9. ios 消息转发初探

    有时候服务器的接口文档上一个数据写的是string类型,这时候你就会直接把它赋值给一个label. 问题来了,有时候这个string的确是string,没有问题,有时候又是NSNumber,当然不管三 ...

  10. Effective Objective-C 2.0 — 第12条:理解消息转发机制

    11 条讲解了对象的消息传递机制 12条讲解对象在收到无法解读的消息之后会发生什么,就会启动“消息转发”(message forwarding)机制, 若对象无法响应某个选择子,则进入消息转发流程. ...

随机推荐

  1. git 命令添加整个文件夹以及文件夹下的内容

    对于一个文件夹提交到服务器上,喜欢用 git add .(后面为".") 这种情况对于一个文件夹的还是很有用的,但出现了多个不同文件夹后,要分别提交就不能这么用了, 可以使用如下指 ...

  2. 简单理解Java的反射

    反射(reflect): JAVA反射机制是在运行状态中,对于任意一个实体类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意方法和属性:这种动态获取信息以及动态调用对象方法的功 ...

  3. HTML DOM 事件对象 ondragend 事件

    学习网站:http://www.runoob.com/jsref/event-ondragend.html 定义和用法 ondragend 事件在用户完成元素或首选文本的拖动时触发. 拖放是 HTML ...

  4. 12-tinyMCE文本编辑器+图片上传预览+页面倒计时自动跳转

    文本编辑器插件:1.将tinymce文件夹全部复制到webContent下2.tinymce/js目录下放 jquery等三个js文件3.语言包:tinymce/js/tinymce/langs目录下 ...

  5. (六)List All Indices

    Now let’s take a peek at our indices: 现在让我们来看看我们的指数: GET /_cat/indices?v And the response: health st ...

  6. kubernete 本地持久化存储 kube-controller-manager的日志输出 + pvc pv 概念 -- storageclass 概念

    1.mysql持久化存储 [root@pserver78 0415villa]# cat latestmysql.yaml |grep -v '^#' apiVersion: v1 kind: Ser ...

  7. linux安装OpenCV以及windows安装numpy、cv2等python2.7模块

    OpenCV(Open Source Computer Vision Library) 是一个基于BSD许可(开源)发行的跨平台计算机视觉库,它具有C ++,C,Python和Java接口,可以运行在 ...

  8. VS2010创建MVC4项目提示错误: 此模板尝试加载组件程序集 “NuGet.VisualStudio.Interop, Version=1.0.0.0, Culture=neutral,

    在安装VS2010时没有安装MVC4,于是后面自己下载安装了(居然还要安装VS2010 SP1补丁包).装完后新建MVC项目时却提示: 错误: 此模板尝试加载组件程序集 “NuGet.VisualSt ...

  9. (转)JMeter学习逻辑控制器

    JMeter中的Logic Controller用于为Test Plan中的节点添加逻辑控制器. JMeter中的Logic Controller分为两类:一类用来控制Test Plan执行过程中节点 ...

  10. Django模板语言初识

    一.Django框架简介 1.MVC框架 MVC,全名是Model View Controller,是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model).视图(View)和控 ...