天天看點

Springboot+RabbitMQ+企業微信發送消息(binaryWang)

一 項目背景  

   系統需要給企業微信群發消息,發現在更新表字段内容的同時給多人發送企業微信群發消息時,系統一直等待所有消息發送完畢後才結束。中間延遲太長,影響系統體驗。

二 解決辦法  

使用rabbitmq進行消息投遞,實作解耦

三 下載下傳安裝

1.首先下載下傳Erlang環境依賴https://www.erlang.org/downloads 輕按兩下安裝

2.rabbitMQ版本需要與Erlang版本對應,對應版本查詢https://www.rabbitmq.com/which-erlang.html

3.rabbitmq下載下傳輕按兩下安裝,官網https://www.rabbitmq.com/install-windows.html

注意:安裝到哪個盤,資料就會存儲在哪個盤,建議安裝到非C槽

4.安裝rabbitmq_mangement可視化插件

(1)使用rabbitmq command prompt

輸入rabbitmq-plugins list查詢插件

輸入rabbitmq-plugins enable rabbitmq_management安裝插件

重新開機服務rabbitmq-server restart

(2)http://localhost:15672/

預設使用者名密碼 guest guest

Springboot+RabbitMQ+企業微信發送消息(binaryWang)
四 和springboot結合

1.添加依賴

    <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-amqp</artifactId>

        </dependency>

2.添加配置

spring:

  # rabbitmq 配置

  rabbitmq:

    host: 127.0.0.1

    port: 5672

    username: guest

    password: guest

3.隊列配置

@Configuration

public class RabbitConfig {

    @Bean

    public Queue queue(){

        return new Queue("helloMQ");

    }

}

 4.簡單的發送消息RabbitHelloWorldController.java

@RestController
@RequestMapping(value = "/rabbit/helloworld")
public class RabbitHelloWorldController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @GetMapping
    public void helloWorld() {
        rabbitTemplate.convertAndSend("helloMQ", "HelloWorld!" + LocalDateTime.now().toString());
    }
}
           

5. 接收消息:

RabbitHelloWorldListener.java

@Component
@RabbitListener(queues = "helloMQ")
public class RabbitMQListener {
    private Logger logger = AutoNamingLoggerFactory.getLogger();

    @RabbitHandler
    public void receiveMessage(String queueMessage) {
        logger.info("Received message:{}", queueMessage);
    }
}
           

五、Springboot+RabbitMQ+企業微信發送消息(binaryWang)

springboot+企業微信開發參照 https://blog.csdn.net/zhaolulu916/article/details/110184511

修改代碼如下

生産者代碼

@RestController
@RequestMapping(value = "/rabbit/helloworld")
public class RabbitHelloWorldController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
  
    @GetMapping
    public void helloWorld() {
          String username="whale";
          String message="你好";
          String context=username+“@”+message;
          rabbitMQTemplate.convertAndSend("rabbitMQ",context);
    }
}
           

消費者代碼

@Component
public class RabbitMQWorldListener {

    @Autowired
    private QywxService qywxService;

    @RabbitListener(queues = "rabbitMQ")
    public void receiveMessage(String queueMessage) throws WxErrorException {

        if(queueMessage.length()>0) {
            String[] strs = queueMessage.split("@");
            if (strs.length >= 2)
            qywxService.push(strs[0],strs[1]);
        }

    }
}