如何使用Eclipse Californium在EAP中暴露CoAP端点并映射到REST?

解读

面试官想验证三件事:

  1. 你是否知道JBoss EAP的“非HTTP”端口扩展机制(socket-binding、subsystem、undertow/io子系统)。
  2. 你是否能把Californium这种“纯Java UDP栈”无缝托管到EAP的模块化类加载器与线程池里,而不是写成外挂进程。
  3. 你是否能把CoAP的“观察/异步响应”模型映射到REST的“同步资源”或“Server-Sent Events”,并给出企业级高可用、监控、热更新的落地方案。
    国内金融、运营商项目里,CoAP常用于物联网前置网关,EAP作为后端主站,必须回答“怎么不破坏EAP的域模式、不丢包、不改端口、能灰度”。

知识点

  1. JBoss Modules隔离:californium-core、element-connector、netty-*需打成模块,module.xml中依赖javax.api、sun.jdk、org.jboss.netty(EAP7自带netty 4.x)。
  2. 自定义子系统(extension):继承org.jboss.as.controller.SubsystemExtension,在standalone.xml或domain.xml中注册<coap-endpoint />,绑定到socket-binding name="coap" port="5683"。
  3. MSC(Modular Service Container)生命周期:用Service<CoapServer>把Californium Server注册成MSC Service,依赖SocketBinding与ExecutorService,保证stop时端口释放、线程池归还。
  4. 类加载:Californium默认用JDK DatagramSocket,需通过EndpointManager.setDefaultEndpoint(new CoapEndpoint.Builder().setNetworkConfig(…).setExecutor(MSC提供的线程池).build()),避免自己新建线程。
  5. 映射策略:
    • 简单CRUD:CoAP GET/POST/PUT/DELETE ⇒ @Path("/device/{id}") 的JAX-RS资源,用CDI事件总线解耦。
    • 观察模型:CoAP Observe ⇒ JAX-RS异步Response或SseEventSink,把observation relation注册到单例@ApplicationScoped Bean,EAP集群时用Infinispan缓存observation key,保证fail-over后消息不丢。
  6. 安全:EAP的elytron子系统配置udp-coap-security realm,使用PSK(预共享密钥)或RPK(Raw Public Key),把Californium的DtlsConnectorConfig.Builder.setPskStore(new ElytronPskStore())桥接到elytron的CredentialStore。
  7. 监控:通过wildfly-extension-metrics把CoAP的Exchange数量、RTT、重传率暴露成Micrometer MeterRegistry,接入Prometheus。
  8. 热更新:利用EAP的“reloadable deployment”特性,把coap-mapping.jar放在deployment-scanner目录,修改@Observes CoapMessage后自动重新部署,无需重启CoAP端口。

答案

步骤一:模块化Californium
在$EAP_HOME/modules/system/layers/base/org/eclipse/californium/main下放置

  • californium-core-3.8.0.jar
  • element-connector-3.8.0.jar
  • scandium-3.8.0.jar
    module.xml示例: <module name="org.eclipse.californium" xmlns="urn:jboss:module:1.9"> <resources> <resource-root path="californium-core-3.8.0.jar"/> … </resources> <dependencies> <module name="javax.api"/> <module name="org.jboss.netty"/> </dependencies>
</module>

步骤二:自定义子系统与端口
扩展org.jboss.as.controller.SubsystemExtension,在standalone.xml增加
<extension module="org.example.coap"/>
…
<socket-binding-group name="standard-sockets">
<socket-binding name="coap" port="5683"/>
</socket-binding-group>
<subsystem xmlns="urn:org.example.coap:1.0">
<coap-server security-realm="CoapPskRealm"/>
</subsystem>

步骤三:启动Californium Server
public class CoapServerService implements Service<CoapServer> {
private CoapServer server;
public void start(StartContext context) {
NetworkConfig config = NetworkConfig.createStandardWithoutFile();
config.setInt(Keys.NETWORK_STAGE_RECEIVER_THREADS, 2);
CoapEndpoint.Builder builder = new CoapEndpoint.Builder();
builder.setNetworkConfig(config);
builder.setExecutor(Executors.newFixedThreadPool(4)); // 实际从MSC注入
server = new CoapServer();
server.addEndpoint(builder.build());
server.add(new DeviceResource());
server.start();
}
public void stop(StopContext context) { server.stop(); }
public CoapServer getValue() { return server; }
}

步骤四:映射到REST
@Path("/device")
@ApplicationScoped
public class DeviceRestResource {
@Inject
DeviceService service; // 包含CDI事件

@GET
@Path("/{deviceId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getDevice(@PathParam("deviceId") String id) {
return Response.ok(service.find(id)).build();
}

@POST
@Path("/{deviceId}/command")
@Consumes(MediaType.TEXT_PLAIN)
public void sendCommand(@PathParam("deviceId") String id, String cmd) {
service.sendCoapCommand(id, cmd); // 内部用CoapClient调回5683端口
}
}

DeviceResource.java(CoAP侧)
public class DeviceResource extends CoapResource {
public DeviceResource() { super("device"); }
@Override
public void handleGET(CoapExchange exchange) {
String id = exchange.getRequestOptions().getUriQuery().get(0).split("=")[1];
Device device = CDI.current().select(DeviceService.class).get().find(id);
exchange.respond(ResponseCode.CONTENT, JsonbBuilder.create().toJson(device),
MediaTypeRegistry.APPLICATION_JSON);
}
}

步骤五:集群与观察
使用@Observes @CoapObservation Event<ObservationEvent>把观察关系写入Infinispan缓存“coap-observations”,节点故障时由新节点读取缓存重建关系。

步骤六:灰度与监控
通过/metrics端点暴露coap_requests_total{method="GET"},结合Grafana设置udp丢包率>1%时告警;利用EAP的“deployment-overlay”给不同版本设备推送不同的coap-mapping.jar,实现灰度。

拓展思考

  1. 如果CoAP设备量>100万,EAP线程模型会成为瓶颈,可考虑把Californium的CoapEndpoint换成Netty-based实现,复用EAP的IO子系统worker线程池,减少上下文切换。
  2. 国内等保2.0要求物联网通道必须做国密SM4/SM2,可在Scandium的DTLS握手阶段插入国密算法提供者(通过JCE Provider),并在elytron中新增国密realm。
  3. 未来演进到云原生,可直接用EAP XP 5提供的“layered product”能力,把CoAP子系统打包成Galleon layer,在OpenShift中通过S2I镜像自动叠加,实现“同一个镜像,HTTP+CoAP双协议”输出,降低运维碎片化。