使用HTTP方式推送消息到RabbitMQ

这篇博客展示了如何使用Java通过HTTP API在RabbitMQ中发布JSON消息。代码示例中,作者创建了一个HTTP POST请求,设置了URL、认证信息、消息内容和属性,然后将JSON对象作为消息负载发送到指定的MQ队列。每个消息包含ASIN和国家ID信息,并通过MQ队列进行路由。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:账号

2:密码

3:MQ地址

4:MQ端口

5:MQ队列名

6:消息内容

附JAVA代码:

package site.duanzy.rabbitMq;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @author leo
 * @date 2022/12/2 15:45
 */
public class RabbitMqTest {

    public static void main(String[] args) throws Exception {

        String url = "http://root:123456@10.16.2.31:15672/api/exchanges/%2F/amq.default/publish";



        List<String> list = new ArrayList<>();
        list.add("B088R4H28V");


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("routing_key", "tsc.asin-info.us.queue");
        jsonObject.put("payload_encoding", "string");
        jsonObject.put("payload", "leo");

        JSONObject properties = new JSONObject();
        properties.put("delivery_mode", 1);
        JSONObject headers = new JSONObject();
        properties.put("headers", headers);
        jsonObject.put("properties", properties);

        for (String asin : list) {

            JSONObject message = new JSONObject();
            message.put("asin", asin);
            message.put("countryId", 1);
            jsonObject.put("payload", message.toJSONString());

            String body = jsonObject.toJSONString();

            HttpRequest httpRequest = HttpRequest.post(url);
            HttpResponse result = httpRequest
                    .setUrl(url)
                    .contentLength(body.length())
                    .header("Host", "10.16.2.31")
                    .header("Authorization", "Basic cm9vdDoxMjM0NTY=")
                    .body(body).execute();

            System.out.println(result.body());   // 输出:{"routed":true}
            
        }

    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值