pom文件所需用到的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-ip</artifactId>
</dependency>
添加配置文件注入UnicastSendingMessageHandler类
- 新建config文件 UdpIntegrationClientConfig
- 加注解 @Configuration
- 复制以下代码:
//配置在yml文件中的端口号
@Value("${udp.port}")
private Integer udpPort;
@Bean
@ServiceActivator(inputChannel = "udpOut")
public UnicastSendingMessageHandler unicastSendingMessageHandler() {
UnicastSendingMessageHandler unicastSendingMessageHandler = new UnicastSendingMessageHandler("127.0.0.1", udpPort);
return unicastSendingMessageHandler;
}
定义发送端
- 新建sendMessageClient类
- 添加注解 @Service注入到spring管理
- 添加如下代码
@Autowired
private UnicastSendingMessageHandler unicastSendingMessageHandler;
public void sendMessage(String message) {
logger.info("发送UDP: {}", message);
unicastSendingMessageHandler.handleMessage(MessageBuilder.withPayload(message).build());
logger.info("发送成功");
}
定义接收端
- 新建UDPService类
- 添加 @Server注解
- 接收消息的如下代码:
获取yml文件的UDP端口
@Value("${udp.port}")
private Integer udpPort;
实例化一个UDP消息接收服务
@Bean
public IntegrationFlow integrationFlow() {
logger.info("UDP服务启动成功,端口号为: {}", udpPort);
return IntegrationFlows.from(Udp.inboundAdapter(udpPort)).channel("udpChannel").get();
}
转换器:把接收到的数组转换为String字符
@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;
}
过滤器:对消息进行过滤等作用
@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;
}
路由分发器:可以进行分发消息被那个处理器进行处理
@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 (true) {
return "udpHandle2";
}
return "udpHandle1";
}
处理器:进行消息的处理
@ServiceActivator(inputChannel = "udpHandle2")
public void udpMessageHandle2(String message, @Headers Map<String, Object> headers) throws Exception {
System.out.println("udpHandle2 "+message);
logger.info("UDP2:" + message);
}