Feign入门实例
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
package com.ssc.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; @EnableEurekaClient @SpringBootApplication @EnableFeignClients public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
package com.ssc.demo; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; //@FeignClient注解,这个注解标识当前是一个 Feign 的客户端,value 属性是对应的服务名称,也就是你需要调用哪个服务中的接口。 @FeignClient(value = "eureka-user-provide",fallbackFactory = SysUserClinetFallbackFactory.class) public interface UserRemoteClient { //这个位置的请求路径就是,在这个提供者实例下提供具体服务的路径 @RequestMapping(value = "/user/hello",method = RequestMethod.GET) String hello(); } @Slf4j @Component public class SysUserClinetFallbackFactory implements FallbackFactory<SysUserClient> { @Override public SysUserClient create(Throwable throwable) { return new UserRemoteClient(){ @Override public LoginUser hello() { log.error("调用{}异常:{}"); throwable.printStackTrace(); return null; } }; } }
package com.ssc.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class CallHello { @Autowired private UserRemoteClient userRemoteClient; @GetMapping(value = "/callHello") public String calloHello(){ //此时的调用相当于 http://eureka-user-provide/user/hello String result=userRemoteClient.hello(); System.out.println("调用结果:"+result); return result; } }
server: port: 8099 eureka: client: service-url: defaultZone: http://localhost:8761/eureka instance: instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port} spring: application: name: feign-user-consumer
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现