问题
have a simple Spring-Cloud-Stream project that I try to connect with RabbitMQ, It says its connected but It's not working. Did I do something wrong in the code?
Application.properties
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.cloud.stream.bindings.greetingChannel.destination = greetings
server.port=8080
HelloBinding interface
package com.gateway.cloudstreamproducerrabbitmq;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;
public interface HelloBinding {
@Output("greetingChannel")
MessageChannel greeting();
}
ProducerController
package com.gateway.cloudstreamproducerrabbitmq;
import com.gateway.cloudstreamproducerrabbitmq.HelloBinding;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProducerController {
private MessageChannel greet;
public ProducerController(HelloBinding binding) {
greet = binding.greeting();
}
@GetMapping("/greet/{name}")
public void publish(@PathVariable String name) {
String greeting = "Hello, " + name + "!";
Message<String> msg = MessageBuilder.withPayload(greeting)
.build();
this.greet.send(msg);
}
}
And last I have a @EnableBinding(HelloBinding.class) in the main class that starts the application.
回答1:
To setup spring cloud stream with rabbitmq binder implementation you need to configure this in your pom.xml 1.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
then you define this in your application.properties/yaml
2.
spring:
cloud:
stream:
bindings:
greetingChannel
destination: test.greeting
group: queue
rabbit:
bindings:
greetingChannel:
producer:
transacted: true //optional
EnableBinding(HelloBinding.class)
- Inject binding and use it
helloBinding.greeting().send(MessageBuilder
.withPayload(...)
.build());
- Setup of rabbitMQ properties
来源:https://stackoverflow.com/questions/61293786/spring-cloud-stream-connection-with-rabbitmq