目標:接收來自華爲雲的服務器報警信息,並轉發到釘釘的自定義機器人中java
使用Spring-Integration不只節省了不少配置,還增長了可用性。git
更多關於Spring-Integration的介紹可參照官網:http://spring.io/projects/spring-integration。github
樣例已上傳至Github:https://github.com/hackyoMa/spring-integration-http-demospring
項目基於Spring Boot2.0。apache
依賴:json
<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:api
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目錄):markdown
<?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目錄):app
<?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); }
這樣就能將配置文件中接收地址傳來的參數轉發到轉發地址中去。