Nacos实现服务注册与发现

一 概述

服务注册即服务实例将自身服务信息注册到注册中心包括服务所在的IP和Port,服务版本以及访问协议等。

DNS就是一个经典的服务注册。

服务发现即服务实例通过注册中心,获取到注册到其中的服务实例的信息,通过这些信息去请求他们提供的服务。

由于自动扩缩,故障与升级,整组服务实例会动态变更的问题的存在所以我们需要使用服务于注册中心。

二 Nacos实现服务注册中心

Nacos的安装

Nacos本地访问的地址

服务提供者实例

ProviderApplication.java

@SpringBootApplication
//注解@EnableDiscoveryClient使得注册中心获取应用信息
@EnableDiscoveryClient
public class ProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class, args);
    }
}

@RestController
class EchoController {
    @RequestMapping(value = "/echo/{string}", method = RequestMethod.GET)
    public String echo(@PathVariable String string) {
        return string;
    }
}

application.properties

spring.application.name=service-provider
server.port=8081
#注明Nacos服务的地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
#暴露的端口
management.endpoints.web.exposure.include=*

SpringBoot监测路径

服务消费者实例

ConsumerApplication.java

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ConsumerApplication {

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

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

@FeignClient(name = "service-provider")
interface EchoService {
    @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
    String echo(@PathVariable("str") String str);
}

@RestController
class TestController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private EchoService echoService;

    @RequestMapping(value = "/echo-rest/{str}", method = RequestMethod.GET)
    public String rest(@PathVariable String str) {
        return restTemplate.getForObject("http://service-provider/echo/" + str,
            String.class);
    }

    @RequestMapping(value = "/echo-feign/{str}", method = RequestMethod.GET)
    public String feign(@PathVariable String str) {
        return echoService.echo(str);
    }
}

application.properties

spring.application.name=service-consumer
server.port=18082
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

启动之后注册中心的效果

Nacos对Ribbon接口有扩展,支持负载均衡!

猜你喜欢

转载自blog.csdn.net/calm_encode/article/details/113939532