springboot集成grpc

gRPC 简介

gRPC 是一个现代开源的高性能 RPC 框架,可以在任何环境下运行。它可以有效地将数据中心内和跨数据中心的服务与可插拔支持进行负载均衡、跟踪、健康检查和认证。它也适用于分布式计算,将不同设备、移动应用程序和浏览器连接到后端服务。

主要使用场景:

  • 在微服务架构中有效地连接多个服务(链路跟踪)
  • 将移动设备、浏览器客户端连接到后端服务
  • 生成高效的客户端库

可以从图中看出他是可以跨语言使用的,基于HTTP/2协议传输

分两个端:服务提供方和调用方

依赖:

<dependency>
    <groupId>com.anoyi</groupId>
    <artifactId>spring-boot-starter-grpc</artifactId>
    <version>1.1.2.RELEASE</version>
</dependency>

共用接口:

@GrpcService(server = "user")
public interface UserService {

    void insert(UserEntity userEntity);

    void deleteById(Long id);

    void update(UserEntity userEntity);

    UserEntity findById(Long id);

    List<UserEntity> findAll();

server参数必须填:对应了服务调用方配置文件中的spring.grpc.remote-servers.server值

1、服务提供方

application.yml配置文件:

spring:
  grpc:
    enable: true
    port: 6565

服务提供方实现接口提供服务:(接口实现类的命名的前缀必须与接口名相同)

@Service
public class UserServiceImpl implements UserService {

    /**
     * 模拟数据库存储用户信息
     */
    private Map<Long, UserEntity> userMap = new ConcurrentHashMap<>();

    @Override
    public void insert(UserEntity userEntity) {
        if (userEntity == null){
            log.warn("insert user fail, userEntity is null!");
            return ;
        }
        userMap.putIfAbsent(userEntity.getId(), userEntity);
    }

    // 其他省略

}

2、服务调用方

application.yml配置文件:

spring:
  grpc:
    remote-servers:
      - server: user #这个就是上面注解里配置的接口
        host: 127.0.0.1
        port: 6565
      - server: pay
        host: 192.168.0.3
        port: 6565

主类中添加grpc的服务自动扫描(需要添加扫描位置,由于使用了共用的接口工程,spring boot 无法直接扫描当前工程外部的信息,所以需要手动指定 @GrpcService 的包扫描路径,如果 @GrpcService 定义在当前工程内部,则无需配置 @GrpcService):

@SpringBootApplication
@GrpcServiceScan(basePackages = {"com.anoyi.grpc.facade"})
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

在服务调用方的任何component中使用@Autowaire注入即可

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public UserEntity insertUser(@RequestBody UserEntity userEntity){
        userService.insert(userEntity);
        return userEntity;
    }

    // 省略其他

}

5、基于容器的微服务架构下的应用

spring-boot-starter-grpc 无服务注册中心,在 kubernetes 集群或 docker swarm 集群下轻松使用,只需更改 client 端的配置中的 host 即可,基于容器平台的 DNS 服务,host 配置为 server 端的服务名,就能正常调用。

猜你喜欢

转载自www.cnblogs.com/television/p/9454096.html