SpringCloud Feign的使用代码实例

网友投稿 235 2022-12-12


SpringCloud Feign的使用代码实例

1.官方文档

https://cloud.spring.io/spring-cloud-static/spring-cloud-openfeign/2.2.2.RELEASE/reference/html/

2.添加依赖

org.springframework.boot

spring-boot-starter-web

org.springframework.cloud

spring-cloud-starter-netflix-eureka-client

org.springframework.cloud

spring-cloud-starter-openfeign

3.添加启动类注解

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.boot.SpringApplication;

import org.springframehttp://work.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication

//@MapperScan("cn.ytheng.order_service")

@EnableFeignClients

public class OrderServiceApplication {

public static void main(String[] args) {

SpringApplication.run(OrderServiceApplication.class, args);

}

}

4.添加Feign接口

import org.springframework.cloud.openfeign.FeignClient;

import org.springframework.web.bind.anhttp://notation.GetMapping;

import org.springframework.web.bind.annotation.RequestParam;

/**

*

* 商品服务客户端

* product-service: 调用服务名称,即spring.application.name

*

*/

@FeignClient(name = "product-service")

public interface ProductClient {

@GetMapping("/api/v1/product/find")

String getById(@RequestParam("id") int id);

}

5.添加Controller

import cn.theng.order_service.service.ProductClient;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.anhttp://notation.PostMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;

@RestController

@RequestMapping("/api/v1/order")

public class ProductOrderController {

@Autowired

private ProductClient productClient;

@PostMahttp://pping("/test2")

public Object test2(@RequestParam("product_id") int productId) {

String product = productClient.getById(productId);

return "success";

}

}

6.添加application.yml配置

server:

port: 8781

eureka:

client:

serviceUrl:

defaultZone: http://localhost:8761/eureka/

spring:

application:

name: order-service

#设置调用服务超时时间

#product-service为服务名称,也可以设置为默认值default

feign:

client:

config:

product-service:

connectTimeout: 5000

readTimeout: 11000

7.访问地址


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:SpringBoot异步任务使用方法详解
下一篇:Intellij IDEA 旗舰版创建 Spring MVC 项目踩过的坑
相关文章

 发表评论

暂时没有评论,来抢沙发吧~