学习微服务服务消费者——Feign
生活随笔
收集整理的這篇文章主要介紹了
学习微服务服务消费者——Feign
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
微服務之間的調用除了restTemplate+ribbon,還有一種方式就是Feign
1.新建一個feign服務
build.gradle文件
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.8repositories {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文件
server:port: 8795spring:application:name: service-feigneureka: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”接口,
SayHiService.java文件
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文件
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 {@AutowiredSayHiService sayHiService;@RequestMapping("/hi")public String sayHi(){return sayHiService.sayHiFromClient();} }啟動該項目,訪問http://localhost:8795/hi
和
?
此時發現feign采用基于接口的注解,并且具有負載均衡的功能
?
轉載于:https://my.oschina.net/u/2263272/blog/1925828
總結
以上是生活随笔為你收集整理的学习微服务服务消费者——Feign的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JSON序列化(stringify)对象
- 下一篇: 我们一般的前端开发流程