單獨安裝Rabbit服務並設置啓動,能夠經過瀏覽器訪問,通常訪問地址是http://localhost:15672/ ,用戶名密碼看配置文件的用戶名密碼spring
1 實例化配置類註解瀏覽器
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.core.Queue;;
@Configuration
public class RabbitConfig {異步
@Bean
public Queue OrdersQueue() {
return new Queue("隊列名");
}
}ide
2 service 類註冊監控隊列,注意傳遞的參數類型,容許字符串,實體類等。注意異步操做延遲及回調rabbitmq
@Component
@RabbitListener(queues = "隊列名")
public class RabbitmqOrder {隊列
@RabbitHandler
@RabbitListener(queues = "隊列名")
public void process(OrderModel od,Channel channel) throws IOException, InterruptedException {字符串
//具體業務get
//注意異步操做延遲及回調it
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
System.out.println(message);
channel.basicAck(envelope.getDeliveryTag(), true);
}
};
channel.basicConsume("sendOrder", true, consumer);
Thread.sleep(1000);io
}
3 屬性配置
#spring.rabbitmq.host=localhost
#spring.rabbitmq.port: 5672
#spring.rabbitmq.username=guest
#spring.rabbitmq.password=guest
#spring.rabbitmq.publisher-confirms=true
#spring.rabbitmq.virtual-host=/
#spring.rabbitmq.listener.direct.default-requeue-rejected = true
#spring.rabbitmq.listener.simple.retry.max-attempts= 3
#spring.rabbitmq.listener.simple.retry.enabled= true
#spring.rabbitmq.listener.simple.retry.initial-interval = 2000
4調用方式
@Autowired
private AmqpTemplate rabbitTemplate;
rabbitTemplate.convertAndSend("隊列名", 「參數」);