Rabbitmq+spring

1.配置文件

applicationContext-mq.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:rabbit="http://www.springframework.org/schema/rabbit"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://dev.cdsf.com/schema/webmvc
           http://dev.cdsf.com/schema/webmvc.xsd
           http://www.springframework.org/schema/util
           http://www.springframework.org/schema/util/spring-util-4.1.xsd
           http://www.springframework.org/schema/rabbit
            http://www.springframework.org/schema/rabbit/spring-rabbit-1.7.xsd
           http://drools.org/schema/drools-spring
           http://drools.org/schema/drools-spring.xsd">
    <rabbit:connection-factory id="connectionFactory" host="${mq.host}"
                               port="${mq.port}" username="${mq.user}" password="${mq.password}" virtual-host="${mq.virtualHost}"
                               channel-cache-size="50" connection-timeout="60000" requested-heartbeat="30"/>
    <rabbit:admin connection-factory="connectionFactory"/>
    
    <bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.JsonMessageConverter"></bean>
    
    <bean id="simplemessageConverter" class="org.springframework.amqp.support.converter.SimpleMessageConverter"></bean>

    <!--创建消息队列模板-->
    <rabbit:template id="rabbitTemplateSimp" connection-factory="connectionFactory"
                     exchange="${mq.exchange}" message-converter="simplemessageConverter" />
    <!--定义消息队列-->
    <rabbit:queue name="${mq.server.queue}" durable="false" auto-delete="true" />
    <!-- topic模式 -->
    <rabbit:topic-exchange id="${mq.exchange}" name="${mq.exchange}" durable="false" auto-delete="true" >
        <rabbit:bindings>
            <rabbit:binding queue="${mq.server.queue}" pattern="${mq.server.queue}"></rabbit:binding>
        </rabbit:bindings>
    </rabbit:topic-exchange>
    
    <!-- 消费者 -->
    <bean id="meConsumer" class="com.client.mq.consumer.RmqConsumer"/>
    <bean id="rmqProducer" class="com.client.mq.producer.RmqProducer"/>
    <rabbit:listener-container connection-factory="connectionFactory">
        <rabbit:listener ref="meConsumer" method="onMessage" queues="${mq.server.queue}"/>
    </rabbit:listener-container>
    
</beans>

 

2.生产者

@Component
public class RmqProducer {

    private final Logger logger = LoggerFactory.getLogger(RmqProducer.class);

    @Autowired
    private RabbitTemplate rabbitTemplateSimp;
    
    private Base64.Encoder encoder = Base64.getEncoder();

    /**
     * 发送信息
     *
     * @param msg
     */
    public void sendMessage(ResponsePackage request) {
        try {
            if (request != null) {
                long uuid = request.getHeader().getUuid();
                Map<ClientProtocolEnum, String> routingKeyMap = getRoutingKey(uuid);
                // PC、Androidp平台使用AMQP协议
                if (routingKeyMap.containsKey(ClientProtocolEnum.AMQP)) {
                    rabbitTemplateSimp.convertAndSend(Constants.EX_CHANGE, routingKeyMap.get(ClientProtocolEnum.AMQP),
                            request.getByteBuffer().array());
                }

                // WEBGL平台使用STOMP协议
                if (routingKeyMap.containsKey(ClientProtocolEnum.STOMP)) {
                    rabbitTemplateSimp.convertAndSend(Constants.EX_CHANGE, routingKeyMap.get(ClientProtocolEnum.STOMP),
                            encoder.encode(request.getByteBuffer().array()));
                }
                routingKeyMap = null;
            }
        } catch (Exception e) {
            logger.error("Producer send message fail:", e);
        }
    }
    
    private Map<ClientProtocolEnum, String> getRoutingKey(long uuid) {
        Map<ClientProtocolEnum, String> routingKeyMap = new HashMap<ClientProtocolEnum, String>();


        if (uuid == ClientTypeEnum.ALL.getType()) {
            routingKeyMap.put(ClientProtocolEnum.AMQP, Constants.ROUT_KEY_CLIENT);
            routingKeyMap.put(ClientProtocolEnum.STOMP, Constants.ROUT_KEY_CLIENT_WEBGL);
        }
        if (uuid == ClientTypeEnum.RUNNER.getType()) {
            routingKeyMap.put(ClientProtocolEnum.AMQP, Constants.ROUT_KEY_RUNNER);
            routingKeyMap.put(ClientProtocolEnum.STOMP, Constants.ROUT_KEY_RUNNER_WEBGL);
        }
        if (uuid == ClientTypeEnum.EDITOR.getType()) {
            routingKeyMap.put(ClientProtocolEnum.AMQP, Constants.ROUT_KEY_EDITOR);
            routingKeyMap.put(ClientProtocolEnum.STOMP, Constants.ROUT_KEY_EDITOR_WEBGL);
        }
        if (routingKeyMap.size() == 0) {
            String routingKey = Constants.ROUT_KEY_USER_PREFIX + uuid;
            routingKeyMap.put(ClientProtocolCache.get(uuid), routingKey);
        }

        return routingKeyMap;
    }
}

 

3.消费者

public class RmqConsumer implements MessageListener{

    @Autowired
    private ClientServiceFactory serviceFactory;

    private final Logger logger = LoggerFactory.getLogger(RmqConsumer.class);

    @Autowired
    private TaskExecutor taskExecutor;
    
    private Base64.Decoder decoder = Base64.getDecoder();

    @Override
    public void onMessage(Message message) {
        try {
            byte[] body = message.getBody();
          
            if (message.getMessageProperties().getContentType() != null) {
                String bodyStr = new String(body);
                body = decoder.decode(bodyStr);
                message = new Message(body, message.getMessageProperties());
            }

            Header header = transHeader(body);
            handleMessage(header, message);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    private void handleMessage(final Header header, final Message message){
        int messageId = header.getMessageId();
        final ClientService clientService = serviceFactory.getLogic(messageId);
        if (clientService == null) {
            logger.warn("rejected service message id:{}", messageId);
            return;
        }
       
        ClientProtocolCache.put(header.getUuid(), message.getMessageProperties().getContentType() == null ? ClientProtocolEnum.AMQP : ClientProtocolEnum.STOMP);
        logger.info("reveiced service message id:{}", messageId);
        Thread thread = new Thread(){

            public void run(){
                clientService.execute(message, header);
            }
        };

        StringBuffer threadName = new StringBuffer("Rabbitmq messageId :");
        threadName.append(header.getSeqId());
        threadName.append("_");
        threadName.append(header.getMessageId());
   
        thread.setName(threadName.toString());
        
        taskExecutor.execute(thread);
    }

    /**
     * 获取请求header
     * @param body 请求体
     * @return
     * @throws IOException
     */
    private Header transHeader(byte[] body) throws IOException{
        ByteBuffer byteBuffer = ByteBuffer.wrap(body);
        
        Header header = new Header();
        header.clearHeader();
        header.read(byteBuffer);
        return header;
    }
}

 

其中用到了Springmvc中的线程池TaskExecutor。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个非常流行的Java Web框架,它简化了Java应用程序的开发和部署过程。 RabbitMQ是一个开源的消息代理,它支持多种协议,包括AMQP、STOMP和MQTT等。TLS协议则是一种加密传输协议,它可以保证数据在传输过程中的安全性。 在Spring Boot应用程序中使用RabbitMQ需要引入相应的依赖,可以使用Maven或Gradle来进行管理。同时,为了保证消息的安全传输,我们可以使用TLS协议对消息进行加密传输。 以下是使用Spring Boot和RabbitMQ进行消息传输并加密的简单示例: 1. 引入依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-rsa</artifactId> </dependency> ``` 2. 配置RabbitMQ和TLS 在application.properties文件中添加以下配置: ```properties spring.rabbitmq.host=localhost spring.rabbitmq.port=5671 spring.rabbitmq.username=user spring.rabbitmq.password=password spring.rabbitmq.ssl.enabled=true spring.rabbitmq.ssl.key-store=file:/path/to/keystore spring.rabbitmq.ssl.key-store-password=changeit spring.rabbitmq.ssl.trust-store=file:/path/to/truststore spring.rabbitmq.ssl.trust-store-password=changeit ``` 其中,key-store和trust-store分别为用于TLS加密的密钥库和信任库文件路径,需要根据实际情况进行配置。 3. 发送和接收消息 在Spring Boot应用程序中使用RabbitTemplate来发送和接收消息,示例代码如下: ```java @Service public class RabbitMQService { @Autowired private RabbitTemplate rabbitTemplate; public void send(String message) { rabbitTemplate.convertAndSend("exchange", "routingKey", message); } @RabbitListener(queues = "queue") public void receive(String message) { System.out.println("Received message: " + message); } } ``` 其中,send方法用于发送消息,receive方法用于接收消息。在这个例子中,我们将消息发送到名为exchange的交换机,使用名为routingKey的路由键进行路由,然后将消息发送到名为queue的队列中进行消费。 以上就是在Spring Boot应用程序中使用RabbitMQ和TLS进行消息传输的简单示例。需要注意的是,这只是一个基本的示例,实际应用中还需要进行更多的配置和处理,以确保消息传输的安全和可靠性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值