配置类
在application.yml中添加
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
DirectConfig配置类
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DirectConfig {
public final static String DIRECTQUEUE = "direct";
@Bean
public Queue queue(){
return new Queue(DIRECTQUEUE);
}
}
生产者
DirectSender
import com.gebiwangdaye.rabbitmq.config.DirectConfig;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class DirectSender {
@Autowired
private AmqpTemplate amqpTemplate;
public void send(){
String context = "发送消息 ================== direct";
System.out.println(context);
this.amqpTemplate.convertAndSend(DirectConfig.DIRECTQUEUE,context);
}
}
消费者
DirectReceiver
import com.gebiwangdaye.rabbitmq.config.DirectConfig;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queues = DirectConfig.DIRECTQUEUE)
public class DirectReceiver {
@RabbitHandler
public void process(String hello) {
System.out.println("接收到消息 : " + hello);
}
}
测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitmqApplicationTests {
@Autowired
private DirectSender directSender;
@Test
public void testDirectExchange(){
for (int i = 0;i < 30;i++){
directSender.send();
}
}
}