单独安装Rabbit服务并设置启动,可以通过浏览器访问,一般访问地址是http://localhost:15672/ ,用户名密码看配置文件的用户名密码
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("队列名");
}
}
2 service 类注册监控队列,注意传递的参数类型,允许字符串,实体类等。注意异步操作延迟及回调
@Component
@RabbitListener(queues = "队列名")
public class RabbitmqOrder {
@RabbitHandler
@RabbitListener(queues = "队列名")
public void process(OrderModel od,Channel channel) throws IOException, InterruptedException {
//具体业务
//注意异步操作延迟及回调
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);
}
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("队列名", “参数”);