微服务教程-使用Spring Cloud & Eureka实现服务发现和注册

转载请注明出处 http://www.paraller.com
原文排版地址 点击获取更好阅读体验
分割符下面的配置代表:应用程序使用cloud 环境文件运行
如果你使用了SPRING_PROFILES_ACTIVE变量,可以在 manifest.yml or, on Cloud Foundry Lattice, your Docker file.配置这个变量

在我的发布脚本中设置了APPLICATION_DOMAIN 环境变量,告诉服务外部的关联地址。
在Eureka监控界面下点击刷新,30秒后你会看到你的服务已经注册好了。

使用 Ribbon 实现客户端的负载均衡

Spring Cloud 中关联其他服务使用的是 spring.application.name . 当我们构建 Spring Cloud-based 的服务的时候,这个值可以在很多上下文中被用到

为的是让客户端基于一些上下文信息,去决定哪一个服务将会被连接使用, Spring Cloud 把client-side load-balancing用途的 Ribbon集成进来了。
看一下示例,直接使用 Eureka然后使用Ribbon.

package passport;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class)
                .web(false)
                .run(args);
    }
}

@Component
class DiscoveryClientExample implements CommandLineRunner {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Override
    public void run(String... strings) throws Exception {
        discoveryClient.getInstances("photo-service").forEach((ServiceInstance s) -> {
            System.out.println(ToStringBuilder.reflectionToString(s));
        });
        discoveryClient.getInstances("bookmark-service").forEach((ServiceInstance s) -> {
            System.out.println(ToStringBuilder.reflectionToString(s));
        });
    }
}

@Component
class RestTemplateExample implements CommandLineRunner {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public void run(String... strings) throws Exception {
        // use the "smart" Eureka-aware RestTemplate
        ResponseEntity<List<Bookmark>> exchange =
                this.restTemplate.exchange(
                        "http://bookmark-service/{userId}/bookmarks",
                        HttpMethod.GET,
                        null,
                        new ParameterizedTypeReference<List<Bookmark>>() {
                        },
                        (Object) "mstine");

        exchange.getBody().forEach(System.out::println);
    }

}

@Component
class FeignExample implements CommandLineRunner {

    @Autowired
    private BookmarkClient bookmarkClient;

    @Override
    public void run(String... strings) throws Exception {
        this.bookmarkClient.getBookmarks("jlong").forEach(System.out::println);
    }
}

@FeignClient("bookmark-service")
interface BookmarkClient {

    @RequestMapping(method = RequestMethod.GET, value = "/{userId}/bookmarks")
    List<Bookmark> getBookmarks(@PathVariable("userId") String userId);
}

class Bookmark {
    private Long id;
    private String href, label, description, userId;

    @Override
    public String toString() {
        return "Bookmark{" +
                "id=" + id +
                ", href='" + href + '\'' +
                ", label='" + label + '\'' +
                ", description='" + description + '\'' +
                ", userId='" + userId + '\'' +
                '}';
    }

    public Bookmark() {
    }

    public Long getId() {
        return id;
    }

    public String getHref() {
        return href;
    }

    public String getLabel() {
        return label;
    }

    public String getDescription() {
        return description;
    }

    public String getUserId() {
        return userId;
    }
}

The DiscoveryClientExample 演示了使用 Spring Cloud common DiscoveryClient 来查询服务信息. 结果包含了每个服务的域名端口等信息.

The RestTemplateExample 演示了自动配置的 Ribbon-aware RestTemplate 实例.URI 使用了service ID, 而不是一个具体的域名.Eureka注册器会通过这ID找到域名然后给到Ribbon做负载均衡。

The FeignExample 演示如何使用 Spring Cloud Feign 组件. Feign 是 Netflix一个非常便利的项目,可以在接口上使用注释去声明一个 REST API client

可以参考官网的example-github了解feign;

Review

  • Spring Cloud supports 支持 Eureka and Consul service registries (and perhaps more!)
  • The DiscoveryClient API 可以用来查询 Eureka 里面的 service ID信息.
  • Ribbon 是一个 client-side load balancer
  • The RestTemplate 可以在URI中使用 service IDs 来代替 hostnames ,以及可以使用 Ribbon 来选择 service.
  • The Netflix Spring Cloud Feign 组件可以快速的创建一个,灵活的、Eureka-aware 的 REST clients ;

后续

  • Consul有很多特性是 Eureka不具备的,可以去了解一下
  • Round-robin load-balancing 是一种选项,还有其他的策略可以使用。
  • 除了服务发现,我们还可以去关注 single-sign on and security, distributed locks and leadership election, reliability patterns like the circuit breaker, and much more.

参考源码

https://github.com/joshlong/service-registration-and-discovery

Microservice Registration and Discovery with Spring Cloud and Netflix's Eureka

评论

暂无评论