rabbitMq

创建连接

 

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.stereotype.Component;

@Component
public class MqConnectionUtils implements CommandLineRunner{
    public static Channel channel;

    @Value("${component.segment.id}")
    private String segmentId;

    @Autowired
    private RabbitProperties rabbitProperties;

    public void getConnection() throws Exception {
        //定义一个链接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置服务地址
        connectionFactory.setHost(rabbitProperties.getHost());
        //设定端口,注意,这里RabbitMQ的端口,不是管理页面的端口
        connectionFactory.setPort(rabbitProperties.getPort());
        //设定用户名
        connectionFactory.setUsername(rabbitProperties.getUsername());
        //设定密码
        connectionFactory.setPassword(rabbitProperties.getPassword());
        //设定虚拟访问节点
        connectionFactory.setVirtualHost("/");
        Connection connection = connectionFactory.newConnection();
        //创建一个通道
        channel = connection.createChannel();
    }

    @Override
    public void run(String... args) throws Exception {
        getConnection();
    }
}

 

 

发送消息

public BaseResponse pushEvent(String data){
        BaseResponse response = new BaseResponse();
        try {
            if (MqConnectionUtils.channel == null || !MqConnectionUtils.channel.isOpen()){
                mqConnectionUtils.getConnection();
            }
            MqConnectionUtils.channel.basicPublish(tlncExchange,tlncRoutingKey,null,data.getBytes());
            log.info("send message to tlnc:{}",data);
        } catch (Exception e) {
            log.error("pushEvent error: ",e);
            response.setCode("-1");
            response.setData(e.getMessage());
        }
        return response;
    }

 

posted on 2023-01-05 14:28  LJD泊水  阅读(21)  评论(0编辑  收藏  举报