前言
简介
Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
1.启动服务注册中心:spring-cloud-eureka
2.启动服务提供方:spring-cloud-eureka-client【端口为2001】
3.修改spring-cloud-eureka-client中配置的端口号server.port(需与2中不一样),在2的基础上再次启动【端口为2002】
详情如下:SpringCloud教程 | 一.服务的注册与发现(Eureka)
1.新建项目:spring-cloud-eureka-feign
pom.xml
org.springframework.boot
spring-boot-starter-parent
1.5.9.RELEASE
UTF-8
UTF-8
1.8
Edgware.SR1
org.springframework.cloud
spring-cloud-starter-eureka
org.springframework.cloud
spring-cloud-starter-feign
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-tomcat
provided
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
2.application.properties
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka
server.port=8000
spring.application.name=eureka-feign
3.在启动类上用@EnableFeignClients注解开启Feign的功能
package com.gwd;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class SpringCloudEurekaFeignApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudEurekaFeignApplication.class, args);
}
}
4.创建服务TestService
【注意】这里的@FeignClient("eureka-client")是服务提供方的spring.application.name,这与ribbon有所区别
package com.gwd.feign;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @FileName TestService.java
* @Description:TODO
* @author JackHisen(gu.weidong)
* @version V1.0
* @createtime 2018年1月22日 上午10:29:54
* 修改历史:
* 时间 作者 版本 描述
*====================================================
*/
@FeignClient("eureka-client")
public interface TestService {
@RequestMapping("/dc")
public String testFeign();
}
5.创建Controller:TestFeignController
package com.gwd.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.gwd.feign.TestService;
/**
* @FileName TestFeignController.java
* @Description:TODO
* @author JackHisen(gu.weidong)
* @version V1.0
* @createtime 2018年1月22日 上午10:32:52
* 修改历史:
* 时间 作者 版本 描述
*====================================================
*/
@RestController
public class TestFeignController {
@Autowired
private TestService testService;
@RequestMapping("/feign")
public String testFeignController() {
return testService.testFeign();
}
}
6.请求后结果显示: