1 pom.xml
4.0.0 com.example Spring-Cloud-Feign 0.0.1-SNAPSHOT jar Spring-Cloud-Feign Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 2.0.5.RELEASE UTF-8 UTF-8 1.8 Finchley.SR1 org.springframework.cloud spring-cloud-starter-netflix-eureka-server org.springframework.cloud spring-cloud-starter-openfeign org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-starter-netflix-hystrix org.springframework.cloud spring-cloud-starter-netflix-hystrix-dashboard org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import org.springframework.boot spring-boot-maven-plugin
2 配置文件
spring.application.name=feign-consumerserver.port=4001eureka.client.serviceUrl.defaultZone=http://localhost:8080/eureka/
3 启动类
@EnableFeignClients
@EnableFeignClients@SpringCloudApplicationpublic class SpringCloudFeignApplication { public static void main(String[] args) { SpringApplication.run(SpringCloudFeignApplication.class, args); }}
4 根据服务名称来指定服务提供方
//根据服务名称来指定服务提供方@FeignClient(name="service-a",fallback=TestServiceAFallBack.class)public interface TestServiceA { // 通过注解指定访问方式,访问路径,访问参数 @RequestMapping(method = RequestMethod.GET, value = "/getm") String getMessage(@RequestParam("message") String message); }
5 回退类 当service-a getm不可访问是 会返回已经写好的信息
@Componentpublic class TestServiceAFallBack implements TestServiceA{ @Override public String getMessage(String message) { // TODO Auto-generated method stub return "the server is error"; }}
6 编写测试类
@RestControllerpublic class TestController { @Autowired TestServiceA testServiceA; @GetMapping("/test") public String test(String message) { return testServiceA.getMessage(message); } }
7 测试
启动 eureka注册中心 service-a 和feign三个项目
访问 http://127.0.0.1:4001/test?message=123 返回 hello world:123
把服务service-a停掉 再次访问 http://127.0.0.1:4001/test?message=123
返回
the server is error