SpringCloud之Feign

以我个人写的博客系统为例,请求其它微服务API。

一、添加Maven依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

二、启动类增加@EnableFeignClients

复制代码
package com.springcloud.blog;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class BlogAdminApplication {

    public static void main(String[] args) {
        SpringApplication.run(BlogRibbonClientApplication.class, args);
    }

   
}
复制代码

三、编写服务接口类

复制代码
package com.springcloud.blog.example;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient("blog-api")
public interface FeignTestService {


     @GetMapping("/juhe/getIpInfo")
     String getIpInfo(@RequestParam String ip);

}
复制代码

特别注意:

@FeignClient(“blog-api”),其中的blog-api必须是在Eureka Server注册的服务实例。

而对应的@RequestMapping的请求类型必须要写准确,Get请求就写Get,Post请求就写Post,这是其一。

还有就是请求参数是地址栏的形式还是请求体的形式也必须写清楚(记住必须要与对应的微服务URL保持一致,否则请求会出现问题),使用@RequestParam或@RequestBody或@PathVariable的形式写清楚,这是其二。

四、编写Controller

复制代码
package com.springcloud.blog.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/test")
public class TestController {


    @Autowired
    FeignTestService feignTestService;

    @GetMapping(value="/getIp")
    public String getIp(String ip){

        return feignTestService.getIpInfo(ip);
    }
}
复制代码

五、测试

 

posted @   挑战者V  阅读(287)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
历史上的今天:
2019-06-08 VsCode插件与Node.js交互通信
2019-06-08 request:fail url not in domain list
2019-06-08 安卓进阶开发资料之分享
2019-06-08 算法图解之散列表
2018-06-08 shiro实战系列(五)之Authentication(身份验证)
点击右上角即可分享
微信分享提示