SpringCloud

1.openfeign调用本地接口

指定远程地址:@FeignClient   (发起请求的客户端)
指定请求方式:@GetMapping、@PostMapping、@DeleteMapping
指定携带数据:@RequestHeader、@RequestParam、@RequestBody

(1)引入maven

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

 (2)//在启动类开启Feign远程调用功能

@SpringBootApplication
@EnableFeignClients(basePackages = "cn.iocoder.yudao.module") //扫描要远程调用的FeignClient的包,会扫描该包和子包
public class DemoServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoServerApplication.class, args);
    }
}

(3)定义
ProductTestApi的FeignClient客户端,包名在@EnableFeignClients扫描的包名下
package cn.iocoder.yudao.module.system.api.product_test;

@FeignClient(name = "system-server")
@Tag(name = "RPC 服务 - 管理员用户")
@AutoTrans(namespace = PREFIX, fields = {"nickname"})
public interface ProductTestApi
{
    @GetMapping("/rpc-api/system/productTest/get")
    @Operation(summary = "通过用户 ID 查询用户")
    @Parameter(name = "id", description = "用户编号", example = "1", required = true)
    CommonResult<ProductTestRespDTO> getProduct(@RequestParam("id") Long id);
}

(4) FeignClient的实现类ProductTestApiImpl,增加@RestController实现访问接口

package cn.iocoder.yudao.module.system.api.product_test;

@RestController // 提供 RESTful API 接口,给 Feign 调用
@Validated
public class ProductTestApiImpl implements ProductTestApi {
    @Override
    public CommonResult<ProductTestRespDTO> getProduct(Long id) {
        ProductTestRespDTO productTestRespDTO = new ProductTestRespDTO();
        productTestRespDTO.setId(id);
        productTestRespDTO.setNickname("测试");
        productTestRespDTO.setMobile("188228*****");
        return success(productTestRespDTO);
    }
}

 

(5) TestController 调用远程接口 http://localhost:48099/test  获得接口数据

image

image

image

 image

image

 

 


2.openfeign调用远程接口(远程接口不需要有实现类)

单元测试

package cn.iocoder.yudao.module.system.api.product_test;
@FeignClient(value = "weather-client", url = "https://apis.map.qq.com")//接口的域名
public interface WeatherFeignClient {
    @PostMapping("?location=,&key=NZABZ-NXBL4-5KOUS-DK2HY-PXXT6-B4BXT&parameter=")//接口
    String getWeather(@RequestHeader("Authorization") String auth, @RequestParam("token") String token, @RequestParam("cityId") String cityId);
}
@SpringBootTest
@EnableFeignClients(clients = WeatherFeignClient.class)
public class ProductTestServiceImplTest {
    @Resource
    private WeatherFeignClient weatherFeignClient;
    @Test
    void testGetWeather() {
        String weather = weatherFeignClient.getWeather(
                "APPCODE 3223", "fwe", "2182");
        System.out.println(weather);
    }
}

 

 


3.超时设置

配置文件没生效

spring:
  cloud:
    openfeign:
      client:
        config:
          default:
            connectTimeout: 3000
            readTimeout: 5000
          # 第三方天气接口,单独放宽
          weather-client:
            connectTimeout: 5000
            readTimeout: 10000

 

用代码设置超时时间,验证通过

全局配置

package cn.iocoder.yudao.module.demo.framework.rpc.config;

import feign.Request;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {

    @Bean
    public Request.Options feignOptions() {
        return new Request.Options(
                5000,     // connectTimeout
                10000,    // readTimeout
                true      // followRedirects
        );
    }
}

 自定义配置

@FeignClient(value = "weather-client", url = "https://apis.map.qq.com")
public interface WeatherFeignClient {
    @PostMapping("?location=,&key=NZABZ-NXBL4-5KOUS-DK2HY-PXXT6-B4BXT&parameter=")
    String getWeather(@RequestHeader("Authorization") String auth, @RequestParam("token") String token, @RequestParam("cityId") String cityId);
}

 

package cn.iocoder.yudao.module.demo.framework.rpc.config;

import feign.Request;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class WeatherFeignConfig {

    @Bean
    public Request.Options feignOptions() {
        return new Request.Options(
                1, TimeUnit.MILLISECONDS,
                10, TimeUnit.MILLISECONDS,
                true
        );
    }

}

 


4.重试机制

package cn.iocoder.yudao.module.demo.framework.rpc.config;

import feign.Request;
import feign.Retryer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class WeatherFeignConfig {

    @Bean
    public Request.Options feignOptions() {
        return new Request.Options(
                1, TimeUnit.MILLISECONDS,
                10, TimeUnit.MILLISECONDS,
                true
        );
    }

    /**
     * 失败重试配置(重点)
     */
    @Bean
    public Retryer feignRetryer() {
        return new Retryer.Default(
                200,    // 初始重试间隔(ms)
                1000,   // 最大重试间隔(ms)
                2       // 最大重试次数(不含第一次)
        );
    }
}

 


5.openfeign请求拦截器


6.openfeign响应拦截器


7.fallback兜底返回

@FeignClient(name = ApiConstants.NAME, configuration = XTokenRequestInterceptor.class
,fallbackFactory = ProductTestFeignFallbackFactory.class)
@Tag(name = "RPC 服务 - 管理员用户")
@AutoTrans(namespace = PREFIX, fields = {"nickname"})
public interface ProductTestApi //extends AutoTransable<ProductTestRespDTO>
{
    String PREFIX = ApiConstants.PREFIX + "/productTest";
    @GetMapping(PREFIX + "/get")// /rpc-api/system/productTest/get
    @Operation(summary = "通过用户 ID 查询用户")
    @Parameter(name = "id", description = "用户编号", example = "1", required = true)
    CommonResult<ProductTestRespDTO> getProduct(@RequestParam("id") Long id);
}
package cn.iocoder.yudao.module.system.api.product_test;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.system.api.product_test.dto.ProductTestRespDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ProductTestFeignFallbackFactory
        implements FallbackFactory<ProductTestApi> {
    @Override
    public ProductTestApi create(Throwable cause) {
        return new ProductTestApi() {
            @Override
            public CommonResult<ProductTestRespDTO> getProduct(Long id) {
                log.error("ProductTestFeignFallbackFactory:{}", cause.getMessage());
                CommonResult<ProductTestRespDTO> dto = new CommonResult<>();
                dto.setCode(100);
                dto.setMsg("兜底返回");
                return dto;
            }
        };
    }
}
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
sentinel:
  feign:
    enabled: true

 


8.gateway路由


9.gateway断言、自定义断言


10.gateway过滤器


11.gateway默认过滤器,全局过滤器,自定义过滤器

 

posted on 2025-12-10 11:59  上校  阅读(5)  评论(0)    收藏  举报