rabbitmq生产者topic模式简单使用记录

1.maven项目添加mq需要的依赖

        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>3.6.5</version>
        </dependency>

        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>rabbitmq-client</artifactId>
            <version>1.3.0</version>
        </dependency>

2.获取rabbitmq配置文件工具类,properties文件放置在resourse文件夹根目录下,名称为rmq.properties。内容如下:

host=localhost
user=admin
passWord=123456
port=10000

3.读取配置文件工具类

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Random;

public class ProperUtilsMQ {
    public String host;
    public String user;
    public String passWord;
    public String exchange;

    public String queue;
    public String routingKey;
    public String bindingKey;

    public int port;

    public int getPort() {
        return port;
    }

    public String getQueue() {
        queue=exchange+"."+getRandomString(10);
        return queue;
    }

    public String getHost() {
        return host;
    }

    public String getUser() {
        return user;
    }

    public String getPassWord() {
        return passWord;
    }

    public String getExchange() {
        return exchange;
    }

    public String getRoutingKey() {
        return routingKey;
    }

    public String getBindingKey() {
        return bindingKey;
    }

    /**
     *
     * @param exchange
     * @param routingKey
     * @param bindingKey
     */
    public ProperUtilsMQ(String exchange,String routingKey,String bindingKey){
        Properties prop =  new  Properties();
        InputStream ins = this.getClass().getResourceAsStream("/rmq.properties");
        try  {
            prop.load(ins);

            host =prop.getProperty("host");
            user = prop.getProperty("user");
            passWord =prop.getProperty("passWord");
            port=Integer.parseInt(prop.getProperty("port"));

            this.exchange =exchange;
            this.routingKey=routingKey;
            this.bindingKey=bindingKey;

            close(ins);

System.out.println("RabbitMQ:"+host+","+user+","+passWord+","+this.exchange+","+this.routingKey+","+this.bindingKey+","+port);
        }  catch  (IOException e) {
            close(ins);
            e.printStackTrace();
        }
    }

    private void close(InputStream ins){
        try{
            ins.close();
        }catch (Exception e){
            System.out.println("输入流关闭异常:"+e);
        }
    }

    /**
     * 用于生成随机队列名
     * @param length  随机队列名长度
     * @return  随机队列名
     */
    public String getRandomString(int length){
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//含有字符和数字的字符串
        Random random = new Random();//随机类初始化
        StringBuffer sb = new StringBuffer();//StringBuffer类生成,为了拼接字符串

        for (int i = 0; i < length; ++i) {
            int number = random.nextInt(62);// [0,62)

            sb.append(str.charAt(number));
        }
        return "Server_"+this.routingKey+this.bindingKey+sb.toString();
    }
}

4.rabbitmq发送topic通配符模式工具

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

public class MQTopicPublish {
    private static String IP,user,password,EXCHANGE_NAME;
    private static String EXCHANGE_TYPE = "topic";
    private static boolean EXCHANGE_DURABLE = true;

    private Connection connection;
    private Channel channel;

    public MQTopicPublish(String IP, String user, String password, String EXCHANGE_NAME){
        this.IP = IP;
        this.user = user;
        this.password = password;
        this.EXCHANGE_NAME = EXCHANGE_NAME;
    }

    /**
     * 发布消息
     * @param routingKey routingKey
     * @param msg 消息
     * @return
     */
    public boolean Publish(String routingKey,byte[] msg){
            try {
                channel.basicPublish(EXCHANGE_NAME,routingKey,null,msg);
                System.out.println("[x] Sender Sent " + routingKey + " : " + msg);

                finalize();
                return true;
            } catch (IOException e) {
                System.out.println("[y] Sender failed to basic publish.");

                finalize();
                return false;
            }
    }

    public void finalize(){
        try {
            channel.close();
            connection.close();
            System.out.println("RabbitMQ channel、connection 关闭成功");
        }catch (Exception e){
            System.out.println("RabbitMQ关闭异常");
        }
    }

    public int BaseConnection(int port){
        /**
         * 创建连接连接到RabbitMQ
         */
        ConnectionFactory factory = new ConnectionFactory();
        //设置MabbitMQ所在主机ip或者主机名
        factory.setHost(IP);
        factory.setPort(port);
        factory.setUsername(user);
        factory.setPassword(password);

        //创建一个连接
        try {
            connection = factory.newConnection();
        } catch (IOException e) {
            System.out.println("[x] 请确认输入的IP地址、用户名、密码是否准确!");
            return  -1;
        } catch (Exception e) {
            System.out.println("[x] 连接RabbitMQ超时,请重试!");
            return  -1;
        }

        //创建一个频道
        try {
            channel = connection.createChannel();
        } catch (IOException e) {
            System.out.println("[x] 创建频道出错,请重试!");
            return -1;
        }

        //声明一个路由器,指定名称、模式、及其是否durable
        try {
            channel.exchangeDeclare(EXCHANGE_NAME,EXCHANGE_TYPE,EXCHANGE_DURABLE);
        } catch (IOException e) {
            System.out.println("[x] 路由器声明失败,请重试!");
            return -1;
        }

        System.out.println("[x] 发布消息者成功连接至RabbitMQ !");
        return 0;
    }
}

5.如何使用,代码段:

//设置交换器和路由键,topic模式下routing-key配置为通配符模式,可自行通配
ProperUtilsMQ properUtils = new ProperUtilsMQ("exchangeName", "routing-keyName", "");
MQTopicPublish mqTopicPublish = new MQTopicPublish(properUtils.getHost(), properUtils.getUser(),properUtils.getPassWord(), properUtils.getExchange());
                
if (mqTopicPublish.BaseConnection(properUtils.getPort()) != 0) {
	System.out.println("连接RabbiqMQ失败");
	return false;
	}

String msg = "message";
byte[] msgByte = message.getBytes();

if (!mqTopicPublish.Publish(properUtils.getRoutingKey(), msgByte )) {
	System.out.println("发送RabbitMQ消息失败");
	return false;
}
return true;

6.至此,mq生产者发送topic模式代码完毕。消费者接受待后续完善。

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值