我有POJO代表给Rabbit MQ的消息。有一个整数负责消息的类型(无论是update
,remove
,add
等等:
public class Message {
private String field1;
private String field2;
private Integer type;
...
<some other fields>
}
我有一个消费者在我的春季启动应用程序中接受此类消息。因此,为了分别处理每种类型,我必须在我的代码中添加一些开关/案例构造。
这种情况有没有更明确的解决方案?
答案 0 :(得分:1)
您可以将Spring Integration与路由器一起使用......
Rabbit Inbound channel adapter -> router ->
路由器根据类型路由到不同的服务激活器(方法)。
修改强>
以下是一个例子:
@SpringBootApplication
public class So47272336Application {
public static void main(String[] args) {
SpringApplication.run(So47272336Application.class, args);
}
@Bean
public ApplicationRunner runner(RabbitTemplate rabbitTemplate) {
return args -> {
rabbitTemplate.convertAndSend("my.queue", new Domain(1, "foo"));
rabbitTemplate.convertAndSend("my.queue", new Domain(2, "bar"));
rabbitTemplate.convertAndSend("my.queue", new Domain(3, "baz"));
};
}
@Bean
public Queue queue() {
return new Queue("my.queue");
}
@Bean
public IntegrationFlow flow(ConnectionFactory connectionFactory) {
return IntegrationFlows.from(Amqp.inboundAdapter(connectionFactory, "my.queue"))
.route("payload.type", r -> r
.subFlowMapping("1", f -> f.handle("bean", "add"))
.subFlowMapping("2", f -> f.handle("bean", "remove"))
.subFlowMapping("3", f -> f.handle("bean", "update")))
.get();
}
@Bean
public MyBean bean() {
return new MyBean();
}
public static class MyBean {
public void add(Domain object) {
System.out.println("Adding " + object);
}
public void remove(Domain object) {
System.out.println("Removing " + object);
}
public void update(Domain object) {
System.out.println("Updating " + object);
}
}
public static class Domain implements Serializable {
private final Integer type;
private final String info;
public Domain(Integer type, String info) {
this.type = type;
this.info = info;
}
public Integer getType() {
return this.type;
}
public String getInfo() {
return this.info;
}
@Override
public String toString() {
return "Domain [type=" + this.type + ", info=" + this.info + "]";
}
}
}