概述
由于HTTP协议对实时数据传输过于慢,为此采用UDP进行数据传输,来看看如何实现的
整合integration
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-ip</artifactId>
</dependency>
创建UDP服务
package io.freeyou.socket.udp.server;
import io.freeyou.modules.internetBehavior.server.InternetBehaviorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
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.ip.udp.UnicastReceivingChannelAdapter;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.ServletContextListener;
import java.util.Map;
@Slf4j
@Component
public class UdpClientServer implements ServletContextListener {
@Value("${freeyou.udp.port:3514}")
private Integer udpPort;
@Resource
private InternetBehaviorService internetBehaviorService;
@Bean("UnicastReceivingChannelAdapter1")
public UnicastReceivingChannelAdapter getUnicastReceivingChannelAdapter() {
UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(udpPort);
adapter.setOutputChannelName("udpChannel");
adapter.setReceiveBufferSize(2048000);
log.info("实例化UDP端口:{}", udpPort);
return adapter;
}
/**
* 转换器
*/
@Transformer(inputChannel = "udpChannel", outputChannel = "udpFilter")
public String transformer(@Payload byte[] payload, @Headers Map<String, Object> headers) {
String message = new String(payload);
return message;
}
/**
* 过滤器
*/
@Filter(inputChannel = "udpFilter", outputChannel = "udpRouter")
public boolean filter(String message, @Headers Map<String, Object> headers) {
return true;
}
/**
* 路由分发处理器
*/
@Router(inputChannel = "udpRouter")
public String router(String message, @Headers Map<String, Object> headers) {
return "udpHandle1";
}
/**
* 最终处理器1
*/
@ServiceActivator(inputChannel = "udpHandle1")
public void udpMessageHandle(String message) throws Exception {
// 可以进行异步处理
/*ObjectMapper objectMapper = new ObjectMapper();
CameraReq req = objectMapper.readValue(message, CameraReq.class);
newLocatorService.storeCameraInfo(req);*/
log.debug("接收udp数据,message:" + message);
internetBehaviorService.sendAliLogStore(message);
}
/**
* 最终处理器2
*/
@ServiceActivator(inputChannel = "udpHandle2")
public void udpMessageHandle2(String message) throws Exception {
log.info("UDP2:" + message);
}
}
配置文件yml
freeyou:
udp:
port: 3514
max-size: 4096
测试结果
UDP客户端工具sockettool下载地址
链接:https://pan.baidu.com/s/18zDilHG6CvMvxVmJlL-5Yw?pwd=xbqa
提取码:xbqa