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

使用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. 在搭建tesseract-OCR环境中遇到问题和反省

    Tesseract,一款由HP实验室开发由Google维护的开源OCR(Optical Character Recognition , 光学字符识别)引擎,特点是开源,免费,支持多语言,多平台. 在搭 ...

  2. Postman安装与使用

    Postman一款非常流行的API调试工具.其实,开发人员用的更多.因为测试人员做接口测试会有更多选择,例如Jmeter.soapUI等.不过,对于开发过程中去调试接口,Postman确实足够的简单方 ...

  3. Redis操作list

    来自:http://www.cnblogs.com/alex3714/articles/6217453.html List操作,redis中的List在在内存中按照一个name对应一个List来存储. ...

  4. 模块简介:(random)(xml,json,pickle,shelve)(time,datetime)(os,sys)(shutil)(pyYamal,configparser)(hashlib)

    Random模块: #!/usr/bin/env python #_*_encoding: utf-8_*_ import random print (random.random()) #0.6445 ...

  5. django 静态文件的配置

    静态文件简介 一.准备文件 Jquery3.3.1文件,文件目录创建 二.创建过程如图 STATIC_URL = '/static/' #静态文件的别名 STATICFILES_DIRS=[ os.p ...

  6. ASP.NET MVC学习系列(4)——MVC过滤器FilterAttribute

    1.概括 MVC提供的几种过滤器其实也是一种特性(Attribute),MVC支持的过滤器类型有四种,分别是:AuthorizationFilter(授权),ActionFilter(行为),Resu ...

  7. typescript 学习笔记

    错的写法 枚举 错误写法 方法可选参 类 子类没有找父类

  8. centos7下kubernetes(17。kubernetes-回滚)

    kubectl apply每次更新应用时kubernetes都会记录下当前配置,保存为一个revision(版次),这样就可以回滚到某个特定的revision 默认配置下,kubernetes只会保留 ...

  9. uWSGI、WSGI和uwsgi

    WSGI wsgi server (比如uWSGI) 要和 wsgi application(比如django )交互,uwsgi需要将过来的请求转给django 处理,那么uWSGI 和 djang ...

  10. python小白——进阶之路——day2天-———容器类型数据(list,set ,tuple,dict,str)

    #容器类型数据 : list tuple # ###列表的特性:可获取,可修改,有序 # 声明一个空列表 listvar = [] print(listvar,type(listvar)) # (1) ...