您的位置:首页 > 编程语言 > Java开发

Spring cloud Eureka服务注册及发现(三)发现使用服务

2017-02-14 17:53 1306 查看
文章参考来源: 翟永超 的 http://blog.didispace.com/springcloud1/

Feign是一个声明式的Web Service客户端,它使得编写Web Serivce客户端变得更加简单。我们只需要使用Feign来创建一个接口并用注解来配置它既可完成。具体Feign的解释请看:Spring Cloud Feign诠释

下面,通过一个例子来展现Feign如何方便的声明对上述computer-service服务的定义和调用。

创建一个Spring Boot工程,配置pom.xml,具体如下:

<!--  1.引入springCloud parent包的继承-->
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.RELEASE</version>
<relativePath />
</parent>
......
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
</dependencies>


配置 application.yml,设置配置服务器地址和eureka配置信息

spring:
profiles:
#默认使用下面哪个配置项。启动项目的时候 可使用 -Dspring.profiles.active=dev 更换使用的配置项
active: test
#服务配置信息
application:
name: eurekaFeign
cloud:
#配置服务器的设置信息
config:
#采用的文件类型 即:生产环境,测试环境。。
profile: ${spring.profiles.active}
#配置服务器的访问地址
uri: http://${config.server.hostname}:${config.server.port} server:
port: ${port}

#一下信息 尽量配置到git文件上,然后通过配置服务器获取
eureka:
client:
#表示是否注册自身到eureka服务器
registerWithEureka: true
#是否从eureka服务器获取注册信息
fetchRegistry: true
registry-fetch-interval-seconds: 30
#开启客户端存活状态监测
healthcheck:
enabled: true
serviceUrl:
#设置Eureka服务器地址
defaultZone: http://${euruka.server.hostname}:${euruka.server.port}/eureka/ 
#将不同的配置以---分割
---
spring:
profiles: test
port: 7080
config:
server:
hostname: 127.0.0.1
port: 8888
---
spring:
profiles: dev
port: 8080
config:
server:
hostname: 127.0.0.1
port: 8888


应用主类中添加@EnableFeignClients注解, 开启Feign功能:

@SpringBootApplication
//启用eureka服务的客户端注解
@EnableDiscoveryClient
//启用Feign模拟WebService客户端
@EnableFeignClients
public class EurekaFeign {

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


定义使用computeService服务的接口

//使用Eureka服务器上注册标识为computeService的服务
@FeignClient("computeService")
public interface ComputeClient {

@RequestMapping(method = RequestMethod.GET, value = "/add")
Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b);
}


使用@FeignClient(“compute-service”)注解来绑定该接口对应compute-service服务

通过Spring MVC的注解来配置compute-service服务下的具体实现。

在web层中调用上面定义的ComputeClient,具体如下:

@RestController
public class ConsumerController {

@Autowired
ComputeClient computeClient;

@RequestMapping(value = "/add", method = RequestMethod.GET)
public Integer add() {
return computeClient.add(10, 20);
}
}


启动服务程序。

访问 http://http://localhost:7080/add 可以看到正常返回结果了。

然后,查看computeService服务控制台,也输出了被调用的日志信息:



查看Eureka控制台界面 eurekaFeign也注册到了服务中。



我们通过Feign以接口和注解配置的方式,轻松实现了对compute-service服务的绑定,这样我们就可以在本地应用中像本地服务一下的调用它。

当部署多台computeService服务的时候,eurekaFeign不需要做任何修改,就可以访问computeService中的任意一台,实现负载均衡。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  springboot eureka
相关文章推荐