引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
    <version>${springboot.version}</version>
</dependency>

添加配置文件

默认配置和一下相同

spring:
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest

配置websocket并启动全功能代理

WebsocketConfig.java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //添加一个服务端点,来接收客户端的连接
        registry.addEndpoint("/gs-guide-websocket")
                //允许跨域
                .setAllowedOrigins("*")
                //开启SockJS支持
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
    	//开启代理可继续配置代理其他信息
        registry.enableStompBrokerRelay("/queue", "/topic");
        registry.setApplicationDestinationPrefixes("/app")
                //使用.替换/
                .setPathMatcher(new AntPathMatcher("."));
        //registry.setUserDestinationPrefix("/user/");
    }
}   

RabbitMQConfig.java

@Configuration
public class RabbitMQConfig {
    //队列名
    public static final String queueName = "iot";

    @Bean
    Queue queue() {
        //队列不持久
        return new Queue(queueName, false);
    }

    @Bean
    TopicExchange exchange() {
        //使用默认的amq.topic换器
        return new TopicExchange("amq.topic");
    }

    @Bean
    Binding binding(Queue queue, TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("latheInfo.#");
    }
}

发送消息

 @Resource
    private RabbitTemplate messagingTemplate;

    /**
     * 发送消息
     * @param message
     * @param topic
     */
    @Override
    public void sendMessage(Object message, String topic) {
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = null;
        try {
            jsonStr = mapper.writeValueAsString(message);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        messagingTemplate.convertAndSend("amq.topic",topic, jsonStr);
    }