1+ package com .didispace .stream ;
2+
3+ import lombok .extern .slf4j .Slf4j ;
4+ import org .springframework .beans .factory .annotation .Autowired ;
5+ import org .springframework .boot .SpringApplication ;
6+ import org .springframework .boot .autoconfigure .SpringBootApplication ;
7+ import org .springframework .cloud .stream .annotation .EnableBinding ;
8+ import org .springframework .cloud .stream .annotation .Input ;
9+ import org .springframework .cloud .stream .annotation .Output ;
10+ import org .springframework .cloud .stream .annotation .StreamListener ;
11+ import org .springframework .integration .annotation .ServiceActivator ;
12+ import org .springframework .integration .support .MessageBuilder ;
13+ import org .springframework .messaging .Message ;
14+ import org .springframework .messaging .MessageChannel ;
15+ import org .springframework .messaging .SubscribableChannel ;
16+ import org .springframework .stereotype .Component ;
17+ import org .springframework .web .bind .annotation .GetMapping ;
18+ import org .springframework .web .bind .annotation .RequestParam ;
19+ import org .springframework .web .bind .annotation .RestController ;
20+
21+
22+ @ EnableBinding (TestApplication .TestTopic .class )
23+ @ SpringBootApplication
24+ public class TestApplication {
25+
26+ public static void main (String [] args ) {
27+ SpringApplication .run (TestApplication .class , args );
28+ }
29+
30+ @ RestController
31+ static class TestController {
32+
33+ @ Autowired
34+ private TestTopic testTopic ;
35+
36+ /**
37+ * 消息生产接口
38+ *
39+ * @param message
40+ * @return
41+ */
42+ @ GetMapping ("/sendMessage" )
43+ public String messageWithMQ (@ RequestParam String message ) {
44+ testTopic .output ().send (MessageBuilder .withPayload (message ).build ());
45+ return "ok" ;
46+ }
47+
48+ }
49+
50+ /**
51+ * 消息消费逻辑
52+ */
53+ @ Slf4j
54+ @ Component
55+ static class TestListener {
56+
57+ @ StreamListener (TestTopic .INPUT )
58+ public void receive (String payload ) {
59+ log .info ("Received payload : " + payload );
60+ throw new RuntimeException ("Message consumer failed!" );
61+ }
62+
63+ /**
64+ * 消息消费失败的降级处理逻辑
65+ *
66+ * @param message
67+ */
68+ @ ServiceActivator (inputChannel = "test-topic.stream-exception-handler.errors" )
69+ public void error (Message <?> message ) {
70+ log .info ("Message consumer failed, call fallback!" );
71+ }
72+
73+ }
74+
75+ interface TestTopic {
76+
77+ String OUTPUT = "example-topic-output" ;
78+ String INPUT = "example-topic-input" ;
79+
80+ @ Output (OUTPUT )
81+ MessageChannel output ();
82+
83+ @ Input (INPUT )
84+ SubscribableChannel input ();
85+
86+ }
87+
88+ }
0 commit comments