一、 feign简介
Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
需要JAVA Spring Cloud大型企业分布式微服务云构建的B2B2C电子商务平台源码 一零三八七七四六二六
简而言之:
Feign 采用的是基于接口的注解
Feign 整合了ribbon
二、创建一个feign的服务
1)新建一个Springboot项目service-feign,它的pom.xml文件如下
复制代码 4.0.0 com.example service-feign 0.0.1-SNAPSHOT jar service-feign Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 1.4.0.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-feign org.springframework.cloud spring-cloud-starter-eureka org.springframework.boot spring-boot-maven-plugin spring-milestones Spring Milestones https://repo.spring.io/milestone false
2)配置application.yml
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/server: port: 8765spring: application: name: service-feign复制代码
3)feign-service的启动类,在启动类上添加@EnableDiscoveryClient @EnableFeignClients
注解,表示用注解开启feign功能。如果标注了@FeignClient的接口和启动类不在一个包下,应该在@EnableFeignClient()中添加所在包
package com.example.demo; 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;@EnableFeignClients@EnableDiscoveryClient@SpringBootApplicationpublic class ServiceFeignApplication { public static void main(String[] args) { SpringApplication.run(ServiceFeignApplication.class, args); }}复制代码
4)定义一个feign接口,通过@FeignClient(“服务名”),来指定调用哪个服务。比如在代码中调用了hello-service服务的“/hello”接口,代码如下,在启动该项目时,@EnableFeignClients注解就会让Feign在指定包下扫描所有标注了@FeignClient的接口
package com.liantong.service; import org.springframework.cloud.netflix.feign.FeignClient;import org.springframework.web.bind.annotation.RequestMapping;@FeignClient("service-helloworld") //向注册中心申请使用service-helloworld客户端public interface HelloService { @RequestMapping("/hello") //表明使用service-helloworld中的“/hello方法” String sayHelloFromClient();}复制代码
5)controller层
package com.liantong.controller; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody; import com.liantong.service.HelloService; @Controllerpublic class HelloController { @Autowired private HelloService hs; @RequestMapping("/hello") @ResponseBody public String hello() { return hs.sayHelloFromClient(); }}复制代码
6)依次启动eureka-server,两个service-helloworld,再启动本项目,完成!