OpenFeign-远程调用

1.优先配置Openfeign

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

去启动类开启功能

@SpringBootApplication
@EnableFeignClients
public class Application {

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

}

声明本地的远程调用

package example.fegin;

import com.example.Product.entity.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = "service-product")//声明一个feign客户端
public interface ProductFeginClient {



    @GetMapping("/product/{id}")
    Product getProductById(@PathVariable("id") Long id);
}

对墨迹天气的远程调用

@FeignClient(value = "weather-client",url = "http://aliv18.data.moji.com")
public interface WeatherFeginClient {
    @PostMapping("/whapi/json/alicityweather/condition")
    String getWeather(@RequestHeader("Authorization") String auth,
                    @RequestParam("token") String token,
                    @RequestParam("cityId") String cityId);
}

测试类写法

@SpringBootTest
public class Weather {
    @Autowired
    WeatherFeginClient weatherFeginClient;

    @Test
    void test(){
        String weather = weatherFeginClient.getWeather("APPCODE 93b7e19861a24c519a7548b17dc16d75",
                "50b53ff8dd7d9fa320d3d3ca32cf8ed1",
                "2182");
        System.out.println(weather);
    }
}

开启日志

logging:
  level:
    com.atguigu.order.feign: debug

配置类写入

@Bean
Logger.Level feignLoggerLevel() {
    return Logger.Level.FULL;
}

超时控制

spring:
  cloud:
    openfeign:
      client:
        config:
          default:
            logger-level: full
            connect-timeout: 1000
            read-timeout: 2000
          service-product:
            logger-level: full
            connect-timeout: 3000
            read-timeout: 5000

 重试机制

@Bean
Retryer retryer(){
    return new Retryer.Default();
}

拦截器

请求拦截器

@Component
public class XTokenRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        System.out.println("启动拦截器");
        template.header("X-Token", UUID.randomUUID().toString());
    }
}

 fallback - 兜底返回

  1. 引入 sentinel
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            </dependency>

  2. 开启熔断
    feign:
      sentinel:
        enabled: true

  3. 编写 fallback 函数
    @FeignClient(value = "service-product",fallback = ProductFeignClientFallback.class) // feign客户端
    public interface ProductFeignClient {
    
    
        //mvc注解的两套使用逻辑
        //1、标注在Controller上,是接受这样的请求
        //2、标注在FeignClient上,是发送这样的请求
        @GetMapping("/product/{id}")
        Product getProductById(@PathVariable("id") Long id);
    
    
    }
    @Component
    public class ProductFeignClientFallback implements ProductFeignClient {
        @Override
        public Product getProductById(Long id) {
            System.out.println("兜底回调....");
            Product product = new Product();
            product.setId(id);
            product.setPrice(new BigDecimal("0"));
            product.setProductName("未知商品");
            product.setNum(0);
    
            return product;
        }
    }

OpenFeign是一个轻量级的基于Spring Cloud的API客户端库,它简化了服务之间的RESTful API调用。以下是使用OpenFeign进行远程调用的基本步骤以及常见的注解: **步骤1: 添加依赖** 首先,在你的Maven或Gradle项目中添加OpenFeign的依赖。例如,如果你使用的是Spring Boot,可以在pom.xml或build.gradle文件中加入: ```xml <!-- Maven --> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-spring-cloudfoundry</artifactId> <version>9.7.0</version> </dependency> // Gradle implementation 'io.github.openfeign:feign-springcloudfoundry:9.7.0' ``` **步骤2: 创建Feign接口** 定义一个接口,代表你要调用的服务的API,通常会使用`@FeignClient`注解指定服务名和URL: ```java import feign.Feign; import feign.Logger; import feign.RequestLine; @FeignClient(name = "example-service", url = "http://localhost:8080") public interface ExampleService { @RequestMapping(value = "/api/users", method = RequestMethod.GET) List<User> getUsers(); // 其他API方法... } ``` 这里`@RequestMapping`用于映射HTTP请求到方法。 **步骤3: 使用实例化客户端** 无需显式创建客户端实例,只需要在需要的地方导入这个接口即可自动创建。例如: ```java @Autowired private ExampleService exampleService; List<User> users = exampleService.getUsers(); ``` **常用注解说明:** - `@FeignClient`: 标记一个接口表示需要调用的远程服务。 - `@RequestMapping`: 映射HTTP请求方法和路径到接口方法。 - `Logger.Level`: 可选,指定Feign如何记录日志,默认是WARN级别,可设置成DEBUG或INFO等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值