记录一个springboot 2.5 带返回的udp适配器

package com.xxxxxx.framework.config;

import com.alibaba.fastjson.JSONObject;
import com.inho.common.core.redis.RedisCache;
import com.inho.framework.websocket.WebSocketServerCommon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.Filter;
import org.springframework.integration.annotation.Router;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.dsl.MessageChannels;
import org.springframework.integration.ip.dsl.Udp;
import org.springframework.integration.ip.udp.UnicastSendingMessageHandler;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;

import java.io.IOException;
import java.net.*;
import java.util.Map;

/**
 * UDP消息接收服务
 *
 * @author wliduo[[email protected]]
 * @date 2020/5/20 14:16
 */
@Configuration
@EnableIntegration
public class UdpListener {

    private static final Logger logger = LoggerFactory.getLogger(UdpListener.class);
    @Autowired
    private RedisCache redisCache;
    @Value("${inho.udp.port}")
    private Integer udpPort;


    /**
     * UDP消息接收服务写法一
     * https://docs.spring.io/spring-integration/reference/html/ip.html#inbound-udp-adapters-java-configuration
     *
     * @param
     * @return org.springframework.integration.ip.udp.UnicastReceivingChannelAdapter
     * @throws
     * @author wliduo[[email protected]]
     * @date 2020/5/14 11:00
     */
    /*@Bean
    public UnicastReceivingChannelAdapter unicastReceivingChannelAdapter() {
        // 实例化一个UDP消息接收服务
        UnicastReceivingChannelAdapter unicastReceivingChannelAdapter = new UnicastReceivingChannelAdapter(udpPort);
        // unicastReceivingChannelAdapter.setOutputChannel(new DirectChannel());
        unicastReceivingChannelAdapter.setOutputChannelName("udpChannel");
        logger.info("UDP服务启动成功,端口号为: {}", udpPort);
        return unicastReceivingChannelAdapter;
    }*/

    /**
     * UDP消息接收服务写法二
     * https://docs.spring.io/spring-integration/reference/html/ip.html#inbound-udp-adapters-java-dsl-configuration
     *
     * @param
     * @return org.springframework.integration.dsl.IntegrationFlow
     * @throws
     * @author wliduo[[email protected]]
     * @date 2020/5/20 16:08
     */
    @Bean
    public IntegrationFlow integrationFlow()  {
        logger.info("UDP服务启动成功,端口号为: {}", udpPort);


        return IntegrationFlows.from(Udp.inboundAdapter(udpPort)).channel("udpChannel")  .get();
    }

    /**
     * .handle((payload, headers) -> {
     *                     String message = new String((byte[]) payload);
     *                     String response = " i am response 22, " + message;
     *                     return response.getBytes();
     *                 }).handle(Udp.outboundAdapter("'udp://127.0.0.1:10000'"))
     *
     * **/
    //可返回例子
  /*  @Bean
    public IntegrationFlow udpInboundFlow() {
        return IntegrationFlows.from(Udp.inboundAdapter(udpPort))
                .handle((payload, headers) -> {
                    String message = new String((byte[]) payload);
                    String response = " i am response , " + message;
                    return response.getBytes();
                })
                .handle(Udp.outboundAdapter("'udp://127.0.0.1:10000'"))
                .get();
    }*/
    /**
     * 转换器
     *
     * @param payload
     * @param headers
     * @return java.lang.String
     * @throws
     * @author wliduo[[email protected]]
     * @date 2020/5/20 15:30
     */
    @Transformer(inputChannel = "udpChannel", outputChannel = "udpFilter")
    public String transformer(@Payload byte[] payload, @Headers Map<String, Object> headers) {
        String message = new String(payload);
        // 转换为大写
        // message = message.toUpperCase();
        // 向客户端响应,还不知道怎么写
        return message;
    }



    /**
     * 过滤器
     *
     * @param message
     * @param headers
     * @return boolean
     * @throws
     * @author wliduo[[email protected]]
     * @date 2020/5/20 15:30
     */
    @Filter(inputChannel = "udpFilter", outputChannel = "udpRouter" )
    public boolean filter(String message, @Headers Map<String, Object> headers) {
        // 获取来源Id
        String id = headers.get("id").toString();
        // 获取来源IP,可以进行IP过滤
        String ip = headers.get("ip_address").toString();
        // 获取来源Port
        String port = headers.get("ip_port").toString();
        // 信息数据过滤
        /*if (message.indexOf("-") < 0) {
            // 没有-的数据会被过滤
            return false;
        }*/
        return true;
    }

    /**
     * 路由分发处理器
     *
     * @param message
     * @param headers
     * @return java.lang.String
     * @throws
     * @author wliduo[[email protected]]
     * @date 2020/5/20 15:35
     */
    @Router(inputChannel = "udpRouter")
    public String router(String message, @Headers Map<String, Object> headers) {
        // 获取来源Id
        String id = headers.get("id").toString();
        // 获取来源IP,可以进行IP过滤
        String ip = headers.get("ip_address").toString();
        // 获取来源Port
        String port = headers.get("ip_port").toString();
        // 筛选,走那个处理器
        if (false) {
            return "udpHandle2";
        }
        return "udpHandle1";
    }

    private String handleMessage(String payload) {
        // 处理接收到的数据
        String response = "Processed: " + payload;
        // 响应客户端
        try (DatagramSocket socket = new DatagramSocket()) {
            byte[] responseData = response.getBytes();
            DatagramPacket packet = new DatagramPacket(responseData, responseData.length, InetAddress.getLocalHost(), 10000);
            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 最终处理器1
     *
     * @param message
     * @return void
     * @throws
     * @author wliduo[[email protected]]
     * @date 2020/5/20 15:12
     */

    @ServiceActivator(inputChannel = "udpHandle1",outputChannel = "replyChannel")
    public void  udpMessageHandle(String message) throws Exception {
        // 可以进行异步处理
        String mapKey ="";
        message = message.trim();
        if(message!=null && message.startsWith("{") && message.endsWith("}")){
            JSONObject jsonObject = JSONObject.parseObject(message) ;
            mapKey = jsonObject.getString("action");
            WebSocketServerCommon.sendInfo(message,mapKey);
            redisCache.setCacheMapValue("groundExperatureDriver",mapKey,jsonObject.toString());
            handleMessage( jsonObject.toString());
        }else {
            logger.error("UDP 掉用参数错误,请检查,参数内容为"+ message);
        }
    }



    /**
     * 最终处理器2
     *
     * @param message
     * @return void
     * @throws
     * @author wliduo[[email protected]]
     * @date 2020/5/14 11:02
     */
    @ServiceActivator(inputChannel = "udpHandle2")
    public void udpMessageHandle2(String message) throws Exception {
        logger.info("UDP2:" + message);
    }

}

猜你喜欢

转载自blog.csdn.net/zhanglixin999/article/details/134071383
2.5