微服務之間的調用除了restTemplate+ribbon,還有一種方式就是Feignjava
1.新建一個feign服務web
build.gradle文件spring
buildscript { ext { springBootVersion = '2.0.4.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } ext { springCloudVersion = 'Finchley.SR1' } dependencies { compile('org.springframework.boot:spring-boot-starter-web') compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') compile('org.springframework.cloud:spring-cloud-starter-openfeign') testCompile('org.springframework.boot:spring-boot-starter-test') } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } }
application.yml文件app
server: port: 8795 spring: application: name: service-feign eureka: client: service-url: defaultZone: http://localhost:8791/eureka/
啓動主方法負載均衡
package com.example.servicefeign; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; @EnableFeignClients @EnableEurekaClient @SpringBootApplication public class ServiceFeignApplication { public static void main(String[] args) { SpringApplication.run(ServiceFeignApplication.class, args); } }
定義一個feign接口,經過@ FeignClient(「服務名」),來指定調用哪一個服務。好比在代碼中調用了service-hi服務的「/hi」接口,eclipse
SayHiService.java文件maven
package com.example.servicefeign; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @FeignClient("eureka-client-say-hi") //要調用的服務名 public interface SayHiService { @RequestMapping(value = "/hi", method = RequestMethod.GET) //要調用的服務的接口路由, String sayHiFromClient(); //括號裏面,可填充要調用的接口的參數 }
HelloController.java文件spring-boot
package com.example.servicefeign; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @Autowired SayHiService sayHiService; @RequestMapping("/hi") public String sayHi(){ return sayHiService.sayHiFromClient(); } }
啓動該項目,訪問http://localhost:8795/hi微服務
和gradle
此時發現feign採用基於接口的註解,而且具備負載均衡的功能