SpringCloud 整和Nacos实现服务发现(采用Http2协议)

  • Post author:
  • Post category:其他




一、引言

本文主要介绍如何使用Nacos作为服务注册中心,并采用Http2来调用服务。

主要技术:

  • SpringCloud、SpringBoot

  • Nacos

  • httpclient

  • undertow Web服务器

  • openfeign

  • okhttp

    主要通过两个项目来完成演示:

  • provide :服务端

  • consumer:客户端

    在这里插入图片描述

  • 将provide和consumer注册到Nacos-server,

  • 服务消费者consumer通过主动轮询获取他所订阅消费的服务信息列表

  • consumer根据获取到的服务信息列表,进行服务调用。



二、Nacos



1. Nacos简介:

官网



2. Nacos环境搭建



三、引入依赖



3.1 整体项目的依赖


...
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>0.2.2.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>com.alibaba.nacos</groupId>
                    <artifactId>nacos-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
            <version>1.1.0</version>
        </dependency>
...
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.1.11.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR4</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>



3.2 服务端

  <dependency>
   	  <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-undertow</artifactId>
      <version>2.2.1.RELEASE</version>
  </dependency>



3.3 客户端

 		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-okhttp</artifactId>
            <version>10.5.0</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.14.4</version>
 		</dependency>



四、编码



4.1 服务端

  1. 启动类
@SpringBootApplication
@EnableDiscoveryClient
public class NacosProviderApplication {

	public static void main(String[] args) {
		SpringApplication.run(NacosProviderApplication.class, args);
	}
}
  • 通过 Spring Cloud 原生注解

    @EnableDiscoveryClient

    开启服务注册发现功能。
  1. 配置application.properties
server.port=8070
# 服务吗名
spring.application.name=provider
# Nacos服务器地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
# 启用Http2支持
server.http2.enabled=true
  1. 光设置

    server.http2.enabled=true

    不起作用,还需要以下配置
@Configuration
public class WebConfig {
    @Bean
    public UndertowServletWebServerFactory embeddedServletContainerFactory() {
        UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
        factory.addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true));
        return factory;
    }
}
  1. 需要调用的服务
@RestController
public class ProviderController {
    @RequestMapping("/hello")
    public String index(@RequestParam String name) {
        return "hello " + name + ",this is first messge";
    }
    @RequestMapping("/add")
    public String add(@RequestParam(value = "a") Integer a,@RequestParam(value = "b") Integer b) {
        return "the sum of a、b is "+String.valueOf(a+b);
    }
}



4.2客户端

  1. 启动类
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class NacosConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(NacosConsumerApplication.class, args);
    }
}
  • @EnableDiscoveryClient:启用服务注册发现功能。
  • @EnableFeignClients:启用feign进行远程调用
  1. 配置application.properties
server.port=8071
# 服务名
spring.application.name=consumer
# Nacos服务器地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
# 启用okhttp
feign.okhttp.enabled=true
  1. feign接口定义
@FeignClient(value= "provider")
@Component
public interface ServiceTransferApi {
    @RequestMapping(value = "/hello")
    String hello(@RequestParam(value = "name") String name);

    @RequestMapping(value = "/add")
    String add1(@RequestParam(value = "a") Integer a,@RequestParam(value = "b") Integer b);
}
  • @FeignClient调用远程服务,value和name功能都一样都为服务名。
  • 我们这里使用OpenFeign组件(Feign的升级版),它对

    RestTemplate

    做了封装,所以我们不需要再手动配置

    RestTemplate

    来实现负载均衡。
  1. 为了使用明文http2,需要手动指定其协议,配置如下
@Configuration
public class HttpClientConfiguration {

    @Bean
    public OkHttpClient okHttpClient() {
        List<Protocol> protocols = new ArrayList<>();
        protocols.add(Protocol.H2_PRIOR_KNOWLEDGE);
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool());
        // 添加拦截器用于打印响应时所使用的协议
        builder.addInterceptor(new ResponseInterceptor());
        builder.protocols(protocols);
        return builder.build();
    }
}
  1. 为了能方便看出用的是什么协议,设置了拦截器
@Slf4j
public class ResponseInterceptor implements Interceptor {
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        try {
            Response response = chain.proceed(request);
            log.info("请求协议:{}",response.protocol());
            return response;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
  1. 调用接口
@RestController
public class ConsumerController {
    @Autowired
    private ServiceTransferApi serviceTransferApi;
    @RequestMapping("/hello/{name}")
    public String index(@PathVariable("name") String name) {
        return serviceTransferApi.hello(name);
    }
    @RequestMapping("/add/{a}/{b}")
    public String add(@PathVariable("a") Integer a,@PathVariable("b") Integer b) {
        return serviceTransferApi.add1(a,b);
    }
}

7.测试

启动服务

进入Nacos管理端查看服务是否已经注册:

在这里插入图片描述

在浏览器输入:

http://localhost:8071/hello/world


返回:hello world,this is first messge 表示服务调用成功

日志打印出:

请求协议:h2_prior_knowledge

表示Http2协议已经手动指定成功。

感谢参考:

https://blog.csdn.net/wangchengming1/article/details/93074755

https://www.jianshu.com/p/9530d58250c7

https://www.larscheng.com/namingservice/



版权声明:本文为HACKERRONGGE原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。