springcloud(二)

来源:互联网 发布:清华北大抢人 知乎 编辑:程序博客网 时间:2024/06/05 19:46

接上一篇,创建好了服务注册中心,接下来创建一个服务,注册到服务中心。
同样,首先创建一个springboot工程,创建一个启动类

@EnableEurekaClient

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

创建相应的配置文件,主要是说明注册到哪个服务中心:

server:    port: 2222spring:    application:        name: feign        http:             encoding:              charset: UTF-8 # the encoding of HTTP requests/responses              enabled: true # enable http encoding support              force: true # force the configured encodingeureka:    client:        serviceUrl:            defaultZone: http://localhost:1111/eureka/log:    level: debugfeign:    hystrix:        enabled: true

首先看@EnableEurekaClient注解,

@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@EnableDiscoveryClientpublic @interface EnableEurekaClient {}

这个注解包含了@EnableDiscoveryClient,

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@Import(EnableDiscoveryClientImportSelector.class)public @interface EnableDiscoveryClient {/** * If true, the ServiceRegistry will automatically register the local server. */boolean autoRegister() default true;}

我们可以看到,这个注解引入了
EnableDiscoveryClientImportSelector

我们可以看到,在方法

@Overridepublic String[] selectImports(AnnotationMetadata metadata) {String[] imports = super.selectImports(metadata);AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(getAnnotationClass().getName(), true));boolean autoRegister = attributes.getBoolean("autoRegister");if (autoRegister) {List<String> importsList = new ArrayList<>(Arrays.asList(imports));importsList.add("org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration");imports = importsList.toArray(new String[0]);}return imports;}

中,会加载引用的类,直接调用了父类的方,而父类的方法中,要根据方法:

@Overrideprotected boolean isEnabled() {return new RelaxedPropertyResolver(getEnvironment()).getProperty("spring.cloud.discovery.enabled", Boolean.class, Boolean.TRUE);}

的结果,决定是否加载配置的类,而只要添加了注解,这个类就会返回true。

而实际

super.selectImports(metadata)

加载的是该类的classloader所在的目录下的META-INF/spring.factories这个文件中配置的类。

配置文件有以下内容:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\org.springframework.cloud.netflix.eureka.config.EurekaClientConfigServerAutoConfiguration,\org.springframework.cloud.netflix.eureka.config.EurekaDiscoveryClientConfigServiceAutoConfiguration,\org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration,\org.springframework.cloud.netflix.ribbon.eureka.RibbonEurekaAutoConfigurationorg.springframework.cloud.bootstrap.BootstrapConfiguration=\org.springframework.cloud.netflix.eureka.config.EurekaDiscoveryClientConfigServiceBootstrapConfigurationorg.springframework.cloud.client.discovery.EnableDiscoveryClient=\org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration


其中关键的加载了

EurekaClientAutoConfiguration

这个类,而这个类中,分别初始化了EurekaClientConfigBean,EurekaInstanceConfigBean,DiscoveryClient,EurekaServiceRegistry,EurekaRegistration等。

其中关键的就是DiscoveryClient,这个接口就是springcloud中client实际去注册和发现服务的接口。其实现类为EurekaDiscoveryClient。

实际上,看EurekaDiscoveryClient的源码,可以发现,真正去注册和发现的是com.netflix.discovery.EurekaClient。他实现了com.netflix.discovery.shared.LookupService

这个接口。看下文档的描述:

* EurekaClient API contracts are: *  - provide the ability to get InstanceInfo(s) (in various different ways) *  - provide the ability to get data about the local Client (known regions, own AZ etc) *  - provide the ability to register and access the healthcheck handler for the client

实际上,springcloud对netflix做了一层封装,我们不需要知道netflix的实现细节,直接用springcloud就可以了。


启动了客户端之后,可以在服务中心的控制台中看到如下日志信息:


客户端也有相应的注册信息,证明我们的服务注册到了服务中心。

也可以登录控制台网页,看到有一个服务注册进去了。

我这里再创建一个客户端,试一下客户端之间的调用。

首先在之前的客户端中,增加一个服务供另一个客户端调用:

/** * Created by liuyan9 on 2017/7/26. */@RestControllerpublic class FeignController {    @RequestMapping(value = "/call" ,method = RequestMethod.GET)    public String home(@RequestParam String name) {        return "I come from feign :" + name;    }}


然后,创建另一个客户端:



我这里就叫another-eureka,配置文件与前一个客户端几乎相同,更改一下端口号为2223。首先创建一个feign类型的调用方式:

/** * Created by liuyan9 on 2017/7/26. */@FeignClient(value = "feign")public interface CallFeignService {    @RequestMapping(value = "call", method = RequestMethod.GET)    String callFeign(@RequestParam(value = "name") String name);}


注意:这里@FeignClient中的value为要调用服务的名称。最关键的是@RequestParam一定要有value属性,否则会报错。

 RequestParam.value() was empty on parameter 0

这是因为:springcloud的feign处理参数和spring是不一样的。

RequestParam requestParam = (RequestParam)ANNOTATION.cast(annotation);String name = requestParam.value();Util.checkState(Util.emptyToNull(name) != null, "RequestParam.value() was empty on parameter %s", new Object[]{Integer.valueOf(parameterIndex)});context.setParameterName(name);Collection query = context.setTemplateParameter(name, (Collection)data.template().queries().get(name));data.template().query(name, query);return true;
如果name是空的话,会抛异常。


在创建一个外部调用的controller,

/** * Created by liuyan9 on 2017/7/26. */@RestControllerpublic class FeignController {    @Autowired    private CallFeignService callFeignService;    @RequestMapping(value = "/another",method = RequestMethod.GET)    public String home(@RequestParam String name) {        return callFeignService.callFeign(name + "another");    }}


启动之后,调用一次http://localhost:2223/another,正确返回结果。

客户端注册和发现服务成功~!不过官网上说可以在访问服务中心时可以利用

http://name:password@localhost:${server.port}/eureka/的方式做安全认证,试了一下,没有成功。

下一次,主要学习一下服务注册和发现的具体源码和这个安全认证的问题。后面继续学习ribbon负载,hystrix断路器,zuul网关等内容。。。。