手把手教你SpringBoot集成RocketMq5.0,gRPC协议

SpringBoot集成RocketMq5.0,gRPC 协议 Java SDK 收发消息,保姆级

  • 手把手教你SpringBoot集成RocketMq5.0,gRPC协议,重点是代码
    • JDK1.8+安装配置
    • rocketmq安装配置
    • rocketmq-dashboard可视化安装
    • SrpingBoot集成RocketMq5.0

手把手教你SpringBoot集成RocketMq5.0,gRPC协议,重点是代码

rocketMq5.0没有找到比较规范、可使用的使用gRpc协议的文章,这里也是试了很久才调通。

JDK1.8+安装配置

很早之前安装的,可能有问题,安装失败联系我

  1. 阿里云盘连接
  2. 安装完后配置环境变量
    手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第1张图片
    手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第2张图片
  3. 验证 javac成功才算是配置成功
    手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第3张图片
    手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第4张图片

rocketmq安装配置

RocketMq官网

  1. 下载二进制版本
    手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第5张图片
  2. 配置环境变量
    手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第6张图片
    路径
    手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第7张图片
  3. 具体需要配置的
    bin->runserver.cmd
    第一个非必改(rocketmq自带配置较大)根据个人电脑配置
    -Xms256m -Xmx256m -Xmn128m
    第二个需要查看是否带双引号
    手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第8张图片
    bin->runbroker.cmd
    第一个非必改(rocketmq自带配置较大)根据个人电脑配置
    -Xms256m -Xmx256m -Xmn128m
    第二个需要查看是否带双引号,有些电脑不带双引号会闪退,我的好像不会,公司服务器会
    手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第9张图片
    conf->broker.conf (亲测改不改没用,启动还要加)
    手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第10张图片
    conf->rmq-proxy.json
    proxy代理端口
{
  "rocketMQClusterName": "DefaultCluster",
  "remotingListenPort":28080,
  "grpcServerPort":28081
}
  1. 启动 bin->cmd (第二个不这样写,第三个起不来,报错)
    start mqnamesrv.cmd
    start mqbroker.cmd -n 127.0.0.1:9876 autoCreateTopicEnable=true
    start mqproxy.cmd -n 127.0.0.1:9876

rocketmq-dashboard可视化安装

RocketMq官网
手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第11张图片
maven编译,maven安装省略,不会百度,再不会建议转行
需修改的application.yml(端口自定义,别被占用)
手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第12张图片
MessageServiceImpl.java(去掉+1,新版本不修改,所有的数据都显示两条,阿里群找的答案,都是大佬,钉钉群21982288)
手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第13张图片
编译,启动,java -jar ***.jar
启动后页面
手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第14张图片
针对5.0.5版本的具体消息无法查看(消息查看有延迟)
手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第15张图片

SrpingBoot集成RocketMq5.0

  1. pom引用

	<dependency>
		<groupId>org.apache.rocketmqgroupId>
		<artifactId>rocketmq-client-javaartifactId>
		<version>5.0.5version>
	dependency>

  1. application.yml配置
    proxy: conf->rmq-proxy.json remotingListenPort
    accessKey: con->plain_acl.yml ->accessKey(最下面的账户)
    secretKey: con->plain_acl.yml ->secretKey(最下面的账户)
rocketmq:
  enabled: true
  accessKey: rocketmq2
  secretKey: 12345678
  proxy: 192.168.25.1:28080
  topic: lo-topic
  consumer:
    group: consumer-group
  1. 消费者RocketMqConsumer (抄别人的)

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.ClientConfiguration;
import org.apache.rocketmq.client.apis.ClientConfigurationBuilder;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.consumer.FilterExpression;
import org.apache.rocketmq.client.apis.consumer.FilterExpressionType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Collections;

@Slf4j
@Component
public class RocketMqConsumer {

    @Value("${rocketmq.proxy}")
    private String proxy;
    @Value("${rocketmq.consumer.group}")
    private String consumerGroup;
    @Value("${rocketmq.topic}")
    private String topic;

    @Bean(name = "MqConsumer")
    @ConditionalOnProperty(value = "rocketmq.enabled", havingValue = "true") //启用禁用
    public void MqConsumer() {
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        ClientConfigurationBuilder builder = ClientConfiguration.newBuilder().setEndpoints(proxy);
        ClientConfiguration configuration = builder.build();
        // 初始化Producer时需要设置通信配置以及预绑定的Topic。
        try {
            log.info("构建mq5.0消费者:proxy:{}, topic:{}, group:{}", proxy, topic, consumerGroup);
            // 订阅消息的过滤规则,表示订阅所有Tag的消息。
            String tag = "*";
            FilterExpression filterExpression = new FilterExpression(tag, FilterExpressionType.TAG);
            provider.newPushConsumerBuilder()
                    .setClientConfiguration(configuration)
                    // 设置消费者分组。
                    .setConsumerGroup(consumerGroup)
                    // 设置预绑定的订阅关系。
                    .setSubscriptionExpressions(Collections.singletonMap(topic, filterExpression))
                    // 设置消费监听器。
                    .setMessageListener(messageView -> {
                        log.info("消费消息:{}", messageView); 
                        String str = StandardCharsets.UTF_8.decode(messageView.getBody()).toString();
                        System.out.println("消费:"+str);
                        return ConsumeResult.SUCCESS;
                    }).build();
            log.info("构建mq5.0消费者成功:proxy:{}, topic:{}, group:{}", proxy, topic, consumerGroup);
        } catch (ClientException e) {
            log.error("构建mq5.0消费者异常:proxy:{}, topic:{}, group:{}", proxy, topic, consumerGroup, e);
        }
    }
}
  1. RocketMqProducer (官网抄的)

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.*;
import org.apache.rocketmq.client.apis.message.Message;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.apache.rocketmq.client.apis.producer.SendReceipt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Slf4j
@Component
public class RocketMqProducer {

    @Value("${rocketmq.accessKey}")
    private String accessKey;
    @Value("${rocketmq.secretKey}")
    private String secretKey;
    @Value("${rocketmq.proxy}")
    private String endpoints;

	//异步
    public void asyncSendMessage(String topic, String messageStr) throws ClientException, InterruptedException, IOException {
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        SessionCredentialsProvider sessionCredentialsProvider = new StaticSessionCredentialsProvider(accessKey, secretKey);
        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder().setEndpoints(endpoints).setCredentialProvider(sessionCredentialsProvider).build();
        Producer producer = provider.newProducerBuilder().setClientConfiguration(clientConfiguration).setTopics(new String[]{topic}).build();
        String tag = "*";
        Message message = provider.newMessageBuilder().setTopic(topic).setTag(tag).setBody(messageStr.getBytes(StandardCharsets.UTF_8)).build();
        CompletableFuture<SendReceipt> future = producer.sendAsync(message);
        ExecutorService sendCallbackExecutor = Executors.newCachedThreadPool();
        future.whenCompleteAsync((sendReceipt, throwable) -> {
            if (null != throwable) {
                log.error("Failed to send message", throwable);
            } else {
                log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());
            }
        }, sendCallbackExecutor);
        Thread.sleep(Long.MAX_VALUE);
        producer.close();
    }

	//同步
    public void sendMessage(String topic, String messageStr) throws ClientException, IOException {
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        SessionCredentialsProvider sessionCredentialsProvider = new StaticSessionCredentialsProvider(accessKey, secretKey);
        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder().setEndpoints(endpoints).setCredentialProvider(sessionCredentialsProvider).build();
        Producer producer = provider.newProducerBuilder().setClientConfiguration(clientConfiguration).setTopics(new String[]{topic}).build();
        String tag = "*";
        System.out.println("消息内容"+messageStr);
        Message message = provider.newMessageBuilder().setTopic(topic).setTag(tag).setBody(messageStr.getBytes(StandardCharsets.UTF_8)).build();
        try {
            SendReceipt sendReceipt = producer.send(message);
            log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());
        } catch (Throwable var13) {
            log.error("Failed to send message", var13);
        }
        producer.close();
    }
}

  1. RocketMqController

import org.apache.rocketmq.client.apis.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class RocketMqController {

    @Value("${rocketmq.topic}")
    private String topic;

    @Autowired
    private RocketMqProducer rocketMqProducer;

    @GetMapping("/rq/send/{message}")
    public String sendMessage(@PathVariable String message) throws ClientException, IOException {
        rocketMqProducer.sendMessage(topic, message);
        System.out.println("测试");
        return "success:message->"+message;
    }

}

  1. 结果
    手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第16张图片
    手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第17张图片
    手把手教你SpringBoot集成RocketMq5.0,gRPC协议_第18张图片
    有问题底部留言

你可能感兴趣的:(RocketMq,SrpingBoot,java,中间件)