SpringCloud之Feign遠程接口映射的實現(xiàn)
一.簡介
SpringCloud是基于Restful的遠程調(diào)用框架,引入Ribbon負載均衡組件后還需要客戶端使用RestTemplate調(diào)用遠程接口,操作起來還顯得繁瑣。SpringCloud提供了遠程接口映射,將遠程Restful服務(wù)映射為遠程接口,消費端注入遠程接口即可實現(xiàn)方法調(diào)用。
二.流程
1.新建遠程接口映射模塊service-api,并引入Feign接口映射依賴
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
</dependencies>
2.編寫接口映射接口
package com.vincent.service;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient("SERVICE-USER")
@RequestMapping("/service-user")
public interface IUserService {
@GetMapping("/detail")
Object detail(@RequestParam("id") Integer id);
}
3.配置消費端application.yml
server: port: 9001 eureka: client: service-url: defaultZone: http://localhost:7001/service-eureka/eureka register-with-eureka: false
4.消費端添加映射模塊依賴
<dependency> <groupId>com.vincent</groupId> <artifactId>service-api</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
5.客戶端注入需要使用的服務(wù)接口映射
package com.vincent.controller;
import com.vincent.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private IUserService userService;
@GetMapping("/detail")
public Object detail(Integer id){
return this.userService.detail(id);
}
}
5.編寫消費端啟動類
package com.vincent;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients({"com.vincent.service"})
@EnableEurekaClient
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class,args);
}
}
@EnableFeignClients 定義Feign接口映射掃描包,IOC容器會自動創(chuàng)建接口實現(xiàn)類
6.訪問 http://localhost:9001/detail?id=1

三.總結(jié)
Feign接口映射服務(wù)端Restful接口會自動依賴Ribbon組件,實現(xiàn)客戶端負載均衡。使用接口調(diào)用消費端遠程接口就像調(diào)用本地方法一樣。
到此這篇關(guān)于SpringCloud之Feign遠程接口映射的實現(xiàn)的文章就介紹到這了,更多相關(guān)SpringCloud Feign遠程接口映射內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot如何監(jiān)聽redis?Key變化事件案例詳解
項目中需要監(jiān)聽redis的一些事件比如鍵刪除,修改,過期等,下面這篇文章主要給大家介紹了關(guān)于SpringBoot如何監(jiān)聽redis?Key變化事件的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-08-08
Java使用jxl包寫Excel文件適合列寬實現(xiàn)
用jxl.jar包,讀寫過Excel文件。也沒有注意最適合列寬的問題,但是jxl.jar沒有提供最適合列寬的功能,上次用到寫了一下,可以基本實現(xiàn)最適合列寬。2013-11-11
SpringBoot+Redis布隆過濾器防惡意流量擊穿緩存
本文主要介紹了SpringBoot+Redis布隆過濾器防惡意流量擊穿緩存,文中根據(jù)實例編碼詳細介紹的十分詳盡,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03

