Spring boot 整合grpc 运用

news2024/10/5 19:16:52

文章目录

    • GRPC基础概念:
    • Protocol Buffers:
      • proto 基础语法:
        • 调用类型:
    • Spring boot 整合 grpc
      • 项目结构:
      • 整合代码:
        • 父 pom
        • proto 模块
        • 服务端:
        • 客户端:
        • 实际调用:
      • 原生集成

GRPC基础概念:

  • GRPC是google开源的一个高性能、跨语言的RPC框架,基于HTTP2协议,基于protobuf 3.x,基于Netty 4.x.

Protocol Buffers:

  • 一个跨语言、跨平台的具有可扩展机制的序列化数据工具。也就是说,我在ubuntu下用python语言序列化一个对象,并使用http协议传输到使用java语言的android客户端,java使用对用的代码工具进行反序列化,也可以得到对应的对象
    1

proto 基础语法:

//指定proto3语法
syntax = "proto3";
//指定作用域
package xxx;
//java_multiple_files = true; 表示在生成Java代码时,每个`.proto`文件都会生成一个独立的Java文件
//声明 rpc 服务接口
//关键字: service 声明需要生成的服务接口"类"
service Greeter {
    // 关键字: rpc 声明服务方法,包括方法名、请求消息(请求体)、相应消息(响应体)
    rpc SayHello(HelloRequest) returns (HelloResponse);
}
//声明请求、响应消息
//关键字: message 声明请求体和响应体
message HelloRequest {
		//标识号 1
    //编号的范围为1 ~ 536,870,911(2^29-1),其中19000~19999不可用。因为Protobuf协议的实现过程中对预留了这些编号
    string name = 1;
		//表示一个人有多个号码
	  repeated string phone = 3;
}
 
message HelloResponse {
    string message = 1;
}
调用类型:
  • Unary RPC 一元RPC调用,也叫简单RPC调用

    rpc SayHello(HelloRequest) returns (HelloResponse);
    
  • 【服务端 Server Stream RPC】流式RPC. 客户端向服务端发送单个请求,服务端以流的方式返回一系列消息。客户端从流中读取消息,直到没有更多的消息。当然,返回的消息当然不是乱序的,gRPC保证单个请求中的消息顺序

    rpc LotsOfReplies(HelloRequest) returns (stream HelloResponse);
    
  • 【客户端 Client Stream RPC】流式RPC调用。客户端向服务端请求一系列的消息,一旦客户端完成消息写入,就会等待服务端读取所有消息并处理它们。gRPC同样会保证单个请求中消息的顺序性

    rpc LotsOfGreetings(stream HelloRequest) returns (HelloResponse);
    
  • 【双向流式调用 Bidirectional Streaming RPC】就是客户端和服务端均以流的方式进行读写消息。这两个流式完全独立的,因此,服务端和客户端可以按照他们喜欢的方式写入和读取流。比如:服务端可以在等待所有的客户端消息发送到后,再处理;也可以交替读取请求、写入响应信息等。当然,每个流中的消息顺序是可以保证的。

    rpc BidiHello(stream HelloRequest) returns (stream HelloResponse);
    

    Channels通道

    gRPC通道提供了一条链接到指定主机和端口号的服务端的链接。他在创建客户端stub的时候使用。客户端可以指定通道参数来修改gRPC的默认行为,例如:打开或者关闭消息压缩。一个通道是有连接和空闲两个状态的

mvn 插件整合,proto编译,生成代码

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>

            <!-- 生成插件 -->
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.5.1:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.11.0:exe:${os.detected.classifier}</pluginArtifact>
                    <protoSourceRoot>${project.basedir}/src/main/proto</protoSourceRoot>
                    <!--设置grpc生成代码到指定路径-->
                    <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
                    <!--生成代码前是否清空目录-->
                    <clearOutputDirectory>false</clearOutputDirectory>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>

        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.6.2</version>
            </extension>
        </extensions>

    </build>

在这里插入图片描述

Spring boot 整合 grpc

大致流程:
1

项目结构:

在这里插入图片描述

整合代码:

父 pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.17</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <groupId>com.xiaoshu</groupId>
  <artifactId>grpc-demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <name>grpc-demo</name>
  <modules>
    <module>grpc-server</module>
    <module>grpc-client</module>
    <module>grpc-proto</module>
  </modules>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <grpc.version>2.15.0.RELEASE</grpc.version>
  </properties>

  <!-- 通用依赖 -->
  <dependencies>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.10</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

  </dependencies>

  <dependencyManagement>
    <dependencies>

      <dependency>
        <groupId>net.devh</groupId>
        <artifactId>grpc-spring-boot-starter</artifactId>
        <version>${grpc.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>

      <dependency>
        <groupId>net.devh</groupId>
        <artifactId>grpc-server-spring-boot-starter</artifactId>
        <version>${grpc.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>

      <dependency>
        <groupId>net.devh</groupId>
        <artifactId>grpc-client-spring-boot-starter</artifactId>
        <version>${grpc.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>

    </dependencies>

  </dependencyManagement>


  <build>

    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>

  </build>

</project>

proto 模块
syntax = "proto3";

package com.ht.meta;
// 生成类的包名
option java_multiple_files = true;
// 生成代码位置
option java_package = "com.meta";
// 定义的所有消息、枚举和服务生成对应的多个类文件,而不是以内部类的形式出现
option java_outer_classname = "HtMetaInfoSyncProto";

service HtMetaInfoSyncService {
  rpc syncMeta (HtMetaSyncRequest) returns (HtMetaSyncResponse) {}
}

//同步类型
enum SyncType {
  ADD  = 0; // 新增
  DEL  = 1; // 删除
  EDIT = 2; // 修改
}

//同步Request
message HtMetaSyncRequest {
  //json内容
  string syncJson = 1;
  //同步类型
  SyncType syncType = 2;
}

//响应Response
message HtMetaSyncResponse {
  //响应码
  string code = 1;
  //提示
  string msg = 2;
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.xiaoshu</groupId>
        <artifactId>grpc-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>grpc-proto</artifactId>
    <packaging>jar</packaging>

    <name>grpc-proto</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>net.devh</groupId>
            <artifactId>grpc-spring-boot-starter</artifactId>
            <version>${grpc.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>

            <!-- 生成插件 -->
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.5.1:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.11.0:exe:${os.detected.classifier}</pluginArtifact>
                    <protoSourceRoot>${project.basedir}/src/main/proto</protoSourceRoot>
                    <!--设置grpc生成代码到指定路径-->
                    <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
                    <!--生成代码前是否清空目录-->
                    <clearOutputDirectory>false</clearOutputDirectory>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>

        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.6.2</version>
            </extension>
        </extensions>

    </build>


</project>

服务端:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.xiaoshu</groupId>
        <artifactId>grpc-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>grpc-server</artifactId>
    <packaging>jar</packaging>

    <name>grpc-server</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>com.xiaoshu</groupId>
            <artifactId>grpc-proto</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>net.devh</groupId>
            <artifactId>grpc-server-spring-boot-starter</artifactId>
            <version>${grpc.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>

    </dependencies>

</project>

server:
  port: 8080

spring:
  application:
    name: spring-boot-grpc-server

# gRPC有关的配置,这里只需要配置服务端口号
grpc:
  server:
    port: 9898

服务端代码:

import com.meta.HtMetaInfoSyncServiceGrpc;
import com.meta.HtMetaSyncRequest;
import com.meta.HtMetaSyncResponse;
import com.meta.SyncType;
import com.util.JsonUtil;
import com.vo.HtMetaClusterInfoVo;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import java.util.List;

/**
 * @author 何永豪
 * @className HtMetaSyncService
 * @description TODO
 * @date 2023/11/6 15:25
 */
@Slf4j
@GrpcService
public class HtMetaSyncService extends HtMetaInfoSyncServiceGrpc.HtMetaInfoSyncServiceImplBase {

    @Override
    public void syncMeta(HtMetaSyncRequest request, StreamObserver<HtMetaSyncResponse> responseObserver) {
        String syncJson = request.getSyncJson();
        log.info("接收到json:{}",syncJson);
        List<HtMetaClusterInfoVo> list = JsonUtil.toList(syncJson, HtMetaClusterInfoVo.class);
        SyncType syncType = request.getSyncType();
        int number = syncType.getNumber();
        log.info("同步类型:{}",number);
        HtMetaSyncResponse syncResponse = HtMetaSyncResponse.newBuilder()
                .setCode("1000")
                .setMsg("同步成功").build();
        responseObserver.onNext(syncResponse);
        responseObserver.onCompleted();
    }

}
客户端:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.xiaoshu</groupId>
        <artifactId>grpc-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>grpc-client</artifactId>
    <packaging>jar</packaging>

    <name>grpc-client</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>com.xiaoshu</groupId>
            <artifactId>grpc-proto</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>net.devh</groupId>
            <artifactId>grpc-client-spring-boot-starter</artifactId>
            <version>${grpc.version}</version>
        </dependency>

    </dependencies>

</project>

yml

server:
  port: 8088

spring:
  application:
    name: local-client

grpc:
  client:
    # gRPC配置的名字,GrpcClient注解会用到
    local-grpc-server:
      # gRPC服务端地址
      address: 'static://127.0.0.1:9898'
      enableKeepAlive: true
      keepAliveWithoutCalls: true
      #认证类型,无加密
      negotiationType: plaintext

客户端stub

import com.meta.HtMetaInfoSyncServiceGrpc;
import com.meta.HtMetaSyncRequest;
import com.meta.HtMetaSyncResponse;
import com.meta.SyncType;
import io.grpc.StatusRuntimeException;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;

/**
 * @author xiaoshu
 */
@Service
public class HtMetaInfoSyncClient {

    @GrpcClient("local-grpc-server")
    private HtMetaInfoSyncServiceGrpc.HtMetaInfoSyncServiceBlockingStub stub;


    public String syncMeta(final String json,final SyncType syncType) {
        try {
            HtMetaSyncResponse htMetaSyncResponse = stub.syncMeta((
                    HtMetaSyncRequest.newBuilder()
                            .setSyncJson(json)
                            .setSyncType(syncType)
                            .build()));
            String code = htMetaSyncResponse.getCode();
            String msg = htMetaSyncResponse.getMsg();
            return code+":"+msg;
        } catch (final StatusRuntimeException e) {
            return "FAILED with " + e.getStatus().getCode().name();
        }
    }

}
实际调用:
@Autowired
private HtMetaInfoSyncClient htMetaInfoSyncClient;

@RequestMapping("/htMetaSync")
public String htMetaSync() {
    String json="";
    return htMetaInfoSyncClient.syncMeta(json, SyncType.ADD);
}

原生集成

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.14</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.xiaoshuzxc</groupId>
    <artifactId>grpc-native-api</artifactId>
    <packaging>jar</packaging>

    <name>grpc-native-api</name>
    <description>grpc原生api整合方式</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <grpc.version>1.29.0</grpc.version>
        <proto.version>3.12.0</proto.version>
        <netty.tcnative.version>2.0.30.Final</netty.tcnative.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.grpc</groupId>
                <artifactId>grpc-bom</artifactId>
                <version>${grpc.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.xiaoshu</groupId>
            <artifactId>grpc-proto</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
        </dependency>

        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
        </dependency>

        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty</artifactId>
        </dependency>

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-tcnative-boringssl-static</artifactId>
            <version>${netty.tcnative.version}</version>
            <scope>runtime</scope>
        </dependency>

    </dependencies>
</project>

import org.springframework.stereotype.Service;
import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Service
public @interface GrpcService {

}

启动grpc服务监听:

import com.annotation.GrpcService;
import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.NettyServerBuilder;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SslContextBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @author 何永豪
 * @className GrpcServer
 * @description TODO
 * @date 2023/11/7 15:56
 */
@Slf4j
public class GrpcServer implements CommandLineRunner, DisposableBean {

    private Server server;

    @Resource
    private AbstractApplicationContext applicationContext;

    @Resource
    private GrpcProperties grpcProperties;

    @Override
    public void destroy() {
        stop();
    }

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

    private SslContextBuilder getSslContextBuilder(){
        SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(new File(grpcProperties.getServerCertPath()), new File(grpcProperties.getServerPrivateKeyPath()));
        sslContextBuilder.trustManager(new File(grpcProperties.getServerTrustCertPath()));
        sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
        return GrpcSslContexts.configure(sslContextBuilder);
    }


    private void start() throws IOException {
        NettyServerBuilder nettyServerBuilder = NettyServerBuilder
                .forPort(grpcProperties.getPort());
//                .sslContext(getSslContextBuilder().build()
//                        );
        scanBeanWithAnnotation(GrpcService.class, BindableService.class)
                .forEach(e->{
                    BindableService bindableService = applicationContext.getBeanFactory().getBean(e, BindableService.class);
                    nettyServerBuilder.addService(bindableService.bindService());
                });
        server = nettyServerBuilder.build().start();
        log.info("grpc start listen {}",grpcProperties.getPort());
        Thread thread = new Thread(() -> {
            try {
                GrpcServer.this.blockUntilShutdown();
            } catch (InterruptedException e) {
                log.error("grpc server stopped");
                throw new RuntimeException(e);
            }
        });
        thread.setDaemon(false);
        thread.start();
    }

    private void stop(){
        if (server !=null){
            server.shutdown();
        }
    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server !=null ){
            server.awaitTermination();
        }
    }

    private <T> Stream<String> scanBeanWithAnnotation(Class<? extends Annotation> annotionType,Class<T> beanType){
        String[] beanNamesForType = applicationContext.getBeanNamesForType(beanType);
        return Stream.of(beanNamesForType).filter(e->{
            BeanDefinition beanDefinition = applicationContext.getBeanFactory().getBeanDefinition(e);
            Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(annotionType);
            if (beansWithAnnotation.containsKey(e)){
                return true;
            }else if (beanDefinition.getSource() instanceof AnnotatedTypeMetadata){
                return AnnotatedTypeMetadata.class.cast(beanDefinition.getSource()).isAnnotated(annotionType.getName());
            }
            return false;
        });
    }

}

服务端:

@Slf4j
@GrpcService
public class HtMetaSyncService extends HtMetaInfoSyncServiceGrpc.HtMetaInfoSyncServiceImplBase {

    @Override
    public void syncMeta(HtMetaSyncRequest request, StreamObserver<HtMetaSyncResponse> responseObserver) {
        String syncJson = request.getSyncJson();
        log.info("接收到json:{}",syncJson);
        SyncType syncType = request.getSyncType();
        int number = syncType.getNumber();
        log.info("同步类型:{}",number);
        HtMetaSyncResponse syncResponse = HtMetaSyncResponse.newBuilder()
                .setCode("1000")
                .setMsg("同步成功").build();
        responseObserver.onNext(syncResponse);
        responseObserver.onCompleted();
    }

}

客户端

import com.config.GrpcProperties;
import com.meta.HtMetaInfoSyncServiceGrpc;
import com.meta.HtMetaSyncRequest;
import com.meta.HtMetaSyncResponse;
import com.meta.SyncType;
import io.grpc.ManagedChannel;
import io.grpc.StatusRuntimeException;
import io.grpc.netty.NettyChannelBuilder;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author xiaoshu
 */
@Component
public class HtMetaInfoSyncClient {

    @Resource
    private GrpcProperties grpcProperties;

    @SneakyThrows
    public String syncMeta(final String json,final SyncType syncType) {
        ManagedChannel channel = null;
        try {
            channel=NettyChannelBuilder.
                    forAddress(grpcProperties.getServerIp(),grpcProperties.getPort())
                    //非加密连接
                    .usePlaintext()
                    //加密
                    //.sslContext(grpcProperties.buildClentSslContext())
                    .build();
            HtMetaInfoSyncServiceGrpc.HtMetaInfoSyncServiceBlockingStub stub = HtMetaInfoSyncServiceGrpc.newBlockingStub(channel);
            HtMetaSyncResponse htMetaSyncResponse = stub.syncMeta((
                    HtMetaSyncRequest.newBuilder()
                            .setSyncJson(json)
                            .setSyncType(syncType)
                            .build()));
            String code = htMetaSyncResponse.getCode();
            String msg = htMetaSyncResponse.getMsg();
            return code+":"+msg;
        } catch (final StatusRuntimeException e) {
            return "FAILED with " + e.getStatus().getCode().name();
        }finally {
            if (Objects.nonNull(channel)){
                channel.shutdown();
            }
        }
    }
}
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 何永豪
 * @className GrpcConfig
 * @description TODO
 * @date 2023/11/7 16:58
 */
@Configuration
public class GrpcConfig {

    @Bean
    @ConditionalOnProperty(value = "grpc.enable",havingValue = "true",matchIfMissing = true)
    public GrpcServer grpcServer(){
        return new GrpcServer();
    }

}
@Component
@ConfigurationProperties(prefix = "grpc")
@Data
public class GrpcProperties {

    private Integer port;

    private String  serverIp;

    private String serverCertPath;

    private String serverPrivateKeyPath;

    private String serverTrustCertPath;

    private String clientCertPath;

    private String clientCertChainPath;

    private String clientPrivateKeyPath;

    /*public SslContext buildClentSslContext() throws SSLException {
        SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
        sslContextBuilder.trustManager(new File(clientCertPath));
        sslContextBuilder.keyManager(new File(clientCertChainPath),new File(clientPrivateKeyPath));
        return sslContextBuilder.build();
    }*/

}
server:
  port: 8077

spring:
  application:
    name: grpc-api

grpc:
  #监听端口
  port: 6100
  #目标IP
  server-ip: 127.0.0.1
  #ssl配置
  server-cert-path: /ca/server/server.crt
  server-private-key-path: /ca/server/server.pem
  server-trust-cert-path: /ca/server/ca.crt

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1191824.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

振南技术干货集:C语言的一些“骚操作”及其深层理解(3)

注解目录 第二章《c语言的一些“操作”及其深层理解》 一、字符串的实质就是指针 &#xff08;如何将 35 转为对应的十六进制字符串”0X23”&#xff1f;&#xff09; 二 、转义符\ &#xff08;打入字符串内部的“奸细”。&#xff09; 三、字符串常量的连接 &#xff…

介绍YOLO-NAS Pose:姿势估计的技术

YOLO-NAS 姿势 YOLO-NAS Pose models是对 Pose Estimation 领域的最新贡献。今年早些时候,Deci 因其突破性的目标检测基础模型 YOLO-NAS 获得了广泛认可。在 YOLO-NAS 成功的基础上,该公司现在推出了 YOLO-NAS Pose 作为其姿势估计的对应产品。该姿势模型在延迟和准确性之间…

FinClip 产品10月报:官网新增PC终端麒麟版、UOS版下载

FinClip 的使命是使您&#xff08;业务专家和开发人员&#xff09;能够通过小程序解决关键业务流程挑战&#xff0c;并完成数字化转型的相关操作。不妨让我们看看在本月的产品与市场发布亮点&#xff0c;看看是否有助于您实现目标。 产品方面的相关动向&#x1f447;&#x1f…

拆分代码 + 动态加载 + 预加载,减少首屏资源,提升首屏性能及应用体验

github 原文地址 我们看一些针对《如何提升应用首屏加载体验》的文章&#xff0c;提到的必不可少的措施&#xff0c;便是减少首屏幕加载资源的大小&#xff0c;而减少资源大小必然会想到按需加载措施。本文提到的便是一个基于webpack 插件与 react 组件实现的一套研发高度自定…

【java】JVM-关于Object o=new Object()

请解释一下对象的创建过程?(半初始化) 加问DCL要不要加volatile问题?(指令重排) 对象在内存中的存储布局?(对象与数组的存储不同) 例如一个class对象中有三个变量&#xff0c;分别是int&#xff08;4bytes&#xff09;&#xff0c;long&#xff08;8bytes&#xff09;&#…

《QT从基础到进阶·十七》QCursor鼠标的不同位置坐标获取

一些常用鼠标图形&#xff1a; 鼠标光标相对于整个电脑屏幕的位置&#xff1a;QCursor::pos() 当前光标相对于当前窗口的位置&#xff1a;this->mapFromGlobal(QCursor::pos()) void MainWindow::mouseReleaseEvent(QMouseEvent* event) {QPoint pos event->pos(); …

学者观察 | 数字经济中长期发展中的区块链影响力——清华大学柴跃廷

导语 区块链是一种全新的分布式基础架构与计算范式&#xff0c;既能利用非对称加密和冗余分布存储实现信息不可篡改&#xff0c;又可以利用链式数据结构实现数据信息可溯源。当前&#xff0c;区块链技术已成为全球数据交易、金融结算、国际贸易、政务民生等领域的信息基础设施…

【word技巧】word文件中的图片,批量提取

如果你需要word文件中的图片做其他事情&#xff0c;除了一张张的进行图片另存为以外&#xff0c;我们还有其他方法可以批量一次性保存word文档中的图片嘛&#xff1f;今天分享两个方法&#xff0c;批量保存word文档图片。 方法一&#xff1a; 将文件进行另存为&#xff0c;在…

“Git 在团队协作中的优化实践“

文章目录 引言&#xff1a;一、Git 简介1.1 Git 基本概念1.2 Git 原理与工作流程 二、 Git 与 SVN 的区别三、Git 的常用命令及操作四、Git 的理论知识&#xff1a;总结&#xff1a; 引言&#xff1a; 随着技术的不断演进和团队的不断发展&#xff0c;代码管理变得越来越重要。…

境电商为什么要做独立站?API一键对接秒上架瞬间拥有全平台几十亿商品和用户!

境电商为什么要做独立站&#xff1f;它的优势又有哪一些&#xff1f; 如果说我们的企业是做b two b的跨境电商&#xff0c;那今天这个内容一定要仔细&#xff0c;API一键对接秒上架瞬间拥有全平台几十亿商品和用户&#xff01; 第一呢&#xff0c;独立站它就是我们自己做的一个…

长安链可验证数据库,保证数据完整性的可信存证方案

近日&#xff0c;长安链发布“可验证数据库”实现了链上链下协同存储及数据完整性保证&#xff0c;显著提升长安链存储能力的可扩展性。 可信存证是联盟链最典型的应用场景&#xff0c;被广泛应用在司法、工业、农业、贸易等领域。联盟链的存证应用主要分为两个阶段&#xff1…

解决方案 |法大大电子合同推动汽车后市场多元数智化发展

近日&#xff0c;商务部等9部门联合发布《关于推动汽车后市场高质量发展的指导意见》&#xff08;以下简称《指导意见》&#xff09;&#xff0c;明确了汽车后市场发展的总体目标和主要任务&#xff0c;系统部署推动汽车后市场高质量发展&#xff0c;促进汽车后市场规模稳步增长…

【kafka】Java客户端代码demo:自动异步提交、手动同步提交及提交颗粒度、动态负载均衡

一&#xff0c;代码及配置项介绍 kafka版本为3.6&#xff0c;部署在3台linux上。 maven依赖如下&#xff1a; <!-- kafka --><dependency><groupId>org.apache.kafka</groupId><artifactId>kafka_2.13</artifactId><version>3.6.0…

QGraphicsView

** QGraphicsView教程及示例代码 ** 1、简介 在Qt界面库中,对于图形的绘制,可以使用 QPainter 实现普通二维图形的绘制,该方法在 paintEvent 事件里编写绘图程序,其本质绘制的图形是位图,这种方法更适合于绘制复杂度不高的固定图形,并且不能实现图项的选择、编辑、拖…

福布斯:Salesforce和ZohoCRM,哪个更适合你?

上周&#xff0c;福布斯发布了《CRM软件指南》&#xff0c;从企业的实际需求出发&#xff0c;通过性价比、功能、可用性、第三方集成、分析工具等多个维度进行比较&#xff0c;最终推选出7家代表厂商。本周&#xff0c;福布斯就其中呼声较高的两家企业Salesforce、Zoho CRM做进…

uniapp和vue3+ts开发小程序,使用vscode提示声明变量冲突解决办法

在uniapp中&#xff0c;我们可能经常会遇到需要在不用的环境中使用不同变量的场景&#xff0c;例如在VUE3中的小程序环境使用下面的方式导入echarts&#xff1a; const echarts require(../../static/echarts.min); 如果不是小程序环境则使用下面的方式导入echarts&#xff…

苹果手机发热发烫是什么原因?看完这篇你就知道了!

苹果手机以其卓越的用户体验和优秀的性能得到了广大用户的喜爱和追捧。在日常使用苹果手机时&#xff0c;我们可能会遇到手机发热发烫的情况。那么&#xff0c;苹果手机发热发烫是什么原因呢&#xff1f;小编将为大家解析这一问题的原因&#xff0c;并为您提供相应的解决方案&a…

mysql隐式转换转换引起的bug

生产环境中遇到一个情况情况 &#xff0c;过滤数据发现过滤不掉相关值情况&#xff0c;具体情况如下 原始数据&#xff1a; CREATE TABLE test (id bigint(11) NOT NULL AUTO_INCREMENT COMMENT 自增id,subject_id bigint(11) NOT NULL DEFAULT 0 COMMENT 主题id,subject_nam…

Java 设计模式——享元模式

目录 1.概述2.结构3.实现3.1.抽象享元3.2.具体享元3.3.享元工厂3.4.测试 4.优缺点5.使用场景6.JDK 源码解析——Integer 类 1.概述 &#xff08;1&#xff09;享元模式 (Flyweight Pattern) 是一种结构型设计模式&#xff0c;主要通过共享对象来减少系统中的对象数量&#xff…