美文网首页
构建微服务(二)服务注册与发现

构建微服务(二)服务注册与发现

作者: millions_chan | 来源:发表于2017-01-18 22:00 被阅读2321次

    本系列的第一篇文章讲解了如何搭建使用consul搭建一个服务注册与发现中心,这篇文章将讲解如何在consul的基础上,实现服务的注册与发现。

    注册与发现服务


    我们先生成并注册一个服务hello(tips:可以使用SPRING INITIALIZR快速生成项目),其依赖有:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-consul-discovery</artifactId>
    </dependency>
    

    引入actuator是为了通过/health对服务实例进行健康监控。然后编写相关服务代码:

    
    @SpringBootApplication
    @RestController
    public class ConsulTestApplication {
        @Autowired
        private Environment environment;
    
        @RequestMapping("/hello")
        public Object hello(@RequestParam String name) {
            if (environment.getActiveProfiles()[0].equalsIgnoreCase("dev")) {
                System.out.println("1111111111111");
                return "hello " + name + ", from instance-1";
            } else {
                System.out.println("2222222222222");
                return "hello " + name + ", from instance-2";
            }
        }
    
        public static void main(String[] args) {
            SpringApplication.run(ConsulTestApplication.class, args);
        }
    }
    

    为了启动2个不同的项目,我们创建application-dev1.propertiesapplication-dev1.properties两个文件,application-dev1.properties内容为:

    server.port=9955
    
    spring.application.name=Consul-Server-1 //应用名称
    spring.cloud.consul.host=192.168.0.101   //连接的consul server ip
    spring.cloud.consul.port=8500 //连接的consul server port
    spring.cloud.consul.enabled=true
    
    spring.cloud.consul.discovery.enabled=true 
    spring.cloud.consul.discovery.instanceId=hello-1 //实例名称
    spring.cloud.consul.discovery.serviceName=hello //服务名称
    spring.cloud.consul.discovery.hostname=192.168.0.102 //服务ip
    spring.cloud.consul.discovery.port=${server.port} //服务port
    spring.cloud.consul.discovery.healthCheckUrl=http://192.168.0.102:${server.port}/health //健康检查url
    spring.cloud.consul.discovery.healthCheckInterval=10s //健康检查频率
    spring.cloud.consul.discovery.tags=dev //tag
    

    application-dev2.properties仅仅将server.port的值换位9556。
    分别请求localhost:9555/hello?name=millions与localhost:9556/hello?name=millions

    实例1输出 实例2输出

    从consul的web ui中也可以看到hello服务的两个实例了:

    consul web ui

    然后,我们生成一个服务消费者,来发现并消费hello服务。

    服务消费者的application.property为:

    server.port=9977
    
    spring.application.name=Consul-Client
    spring.cloud.consul.host=192.168.0.102
    spring.cloud.consul.port=8500
    spring.cloud.consul.discovery.register=false
    

    代码为:

    @SpringBootApplication
    @EnableDiscoveryClient
    @RestController
    public class ConsulDiscoveryClientApplication{
    
        @Autowired
        private LoadBalancerClient loadBalancer;
    
        @Autowired
        private DiscoveryClient discoveryClient;
    
        public static void main(String[] args) {
            SpringApplication.run(ConsulDiscoveryClientApplication.class, args);
        }
    
        /**
         * 从所有服务中选择一个服务
         */
        @RequestMapping("/discover")
        public Object discover() {
            return loadBalancer.choose("hello").getUri().toString();
        }
    
        /**
         * 获取所有服务
         */
        @RequestMapping("/services")
        public Object services() {
            return discoveryClient.getInstances("hello");
        }
    }
    

    访问/discover,将轮流返回http://192.168.0.102:9955以及http://192.168.0.102:9956,即hello服务的两个实例的地址。

    访问/services,将返回:

    [
        {
            "serviceId": "hello",
            "host": "192.168.0.102",
            "port": 9955,
            "secure": false,
            "metadata": {
                "dev": "dev"
            },
            "uri": "http://192.168.0.102:9955"
        },
        {
            "serviceId": "hello",
            "host": "192.168.0.102",
            "port": 9956,
            "secure": false,
            "metadata": {
                "dev": "dev"
            },
            "uri": "http://192.168.0.102:9956"
        }
    ]
    

    使用ribbon、feign消费服务


    至此,我们可以通过服务名hello来发现服务的ip和port了。然而,每次调用服务前都去查找一下服务的地址是一件很麻烦的事,为了解决这个问题,我们可以通过集成ribbon或Feign,简化服务的发现与调用。

    为了使用ribbon或者feign,我们需要导入

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

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

    为了使用ribbon,要加入RestTemplate

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

    而后在控制器中使用:

       @RequestMapping(value = "/ribbon-hello", method = RequestMethod.GET)
        public String ribbonHello() {
            return restTemplate
                        .getForEntity("http://HELLO/hello?name=millions", String.class)
                        .getBody();
        }
    

    而后访问 http://192.168.0.102:9977/ribbon-hello 返回:

    ribbon-hello

    ribbon-hello

    对于feign,先编写一个interface:

    @FeignClient("hello")
    public interface HelloService {
        @RequestMapping(value = "/hello")
        String hello(@RequestParam(name = "name") String name);
    }
    

    而后在控制器中使用它:

        @RequestMapping(value = "/feign-hello", method = RequestMethod.GET)
        public String feignHello() {
            return helloService.hello("millions");
        }
    

    通过访问 http://192.168.0.102:9977/feign-hello 也可得到相同的结果。

    总结


    本文介绍了如何使用consul集群集成spring-cloud进行服务注册与服务发现,更多相关内容请关注后序章节。

    相关文章

      网友评论

          本文标题:构建微服务(二)服务注册与发现

          本文链接:https://www.haomeiwen.com/subject/byybbttx.html