运行代码
package com.by.consumer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author lenovo
* @version 0.1
* @className DirectConsumer 直连交换机
* @date 2024/12/24 17:25
* @since jdk11
*/
@Configuration
@Slf4j
public class DirectConsumer {
//起一个消息队列
@Bean
public Queue directQuery(){
return QueueBuilder.durable("Direct_Q").build();
}
//起一个交换机
@Bean
public Exchange directExchange(){
return ExchangeBuilder.directExchange("Direct").build();
}
//交换机和消息队列进行绑定
@Bean
public Binding Dbinding(){
return BindingBuilder.bind(directQuery()).to(directExchange()).with("rb1").noargs();
}
//消费者消费消息队列的信息,就不会在队列中显示
//@RabbitListener(queues = "Direct_Q") //方法监听D_q1队列,它就是一个消费者了
//如果绑定的队里名称错误,在启动的时候程序就会报错 404 队列找不到
public void Dconsumer(String msg){
log.error("Direct_Q交换机接收到消息->{}", msg);
}
}
package com.by.provider;
import com.by.entity.Ordering;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author lenovo
* @version 0.1
* @className DirectProvider
* @date 2024/12/24 17:41
* @since jdk11
*/
@Service
@Slf4j
public class DirectProvider {
@Autowired
RabbitTemplate rabbitTemplate;
public void send(Ordering ordering) {
//如果交换机的名称是错误的,在投递消息的时候,才会包错 404 找不到 exchange
rabbitTemplate.convertAndSend("Direct", "rb1", ordering);
log.debug("直连生产者发送成功");
}
}
实体类
package com.by.entity;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* @author lenovo
* @version 0.1
* @className Ordering
* @date 2024/12/24 21:34
* @since jdk11
*/
@Data
@Accessors(chain = true)
public class Ordering implements Serializable {
private Long id;
private String name;
private String address;
}
测试
package com.by;
import com.by.entity.Ordering;
import com.by.provider.DirectProvider;
import com.by.provider.TopicProvider;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
class DirectTests {
@Autowired
DirectProvider directProvider;
@Test
void test() throws IOException {
Ordering ordering = new Ordering().setId(1L).setName("张三").setAddress("郑州");
directProvider.send(ordering);
System.in.read();
}
}