可以通过 MockRestServiceServer(restTemplate) 模拟响应 FeignClient 吗?这个例子不起作用:
应用程序类
@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
TicketService.class
@FeignClient("ws")
public interface TicketService {
@RequestMapping(value = "/tickets/")
List<Ticket> findAllTickets();
}
Run Code Online (Sandbox Code Playgroud)
测试配置类
@Profile("test")
@Configuration
public class TestConfig {
@Bean
@Primary
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Run Code Online (Sandbox Code Playgroud)
MyTest.class
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class}, properties = {"ws.ribbon.listOfServers:example.com"})
public class MyTest {
@Autowired
RestTemplate restTemplate;
@Autowired
DispatcherService dispatcherService; // service where the execution of the method TicketService.findAllTickets(); …Run Code Online (Sandbox Code Playgroud) 我正在使用 Feign Client 并禁用负载均衡器
@FeignClient(name = "my-client", url = "${myHost}", configuration = ClientContext.class)
Run Code Online (Sandbox Code Playgroud)
因此,所有功能区属性都将被忽略。我尝试通过不同的方式设置自定义超时,但 Feign 会忽略所有这些,并在 60 秒后抛出 TimeoutException。我尝试使用的方法:在 ClientContext 中:1)
@Value("${feign.connectTimeout:10000}")
private int connectTimeout;
@Value("${feign.readTimeOut:300000}")
private int readTimeout;
@Bean
public Request.Options options() {
return new Request.Options(connectTimeout, readTimeout);
}
Run Code Online (Sandbox Code Playgroud)
2)
@Bean
public Request.Options options() {
return new Request.Options(10_000, 300_000);
}
Run Code Online (Sandbox Code Playgroud)
在 bootstrap.properties 文件中:1)
feign.client.default.connect-timeout=10000
feign.client.default.read-timeout=300000
Run Code Online (Sandbox Code Playgroud)
2)
feign.client.default.config.connect-timeout=10000
feign.client.default.config.read-timeout=300000
Run Code Online (Sandbox Code Playgroud)
3)
feign.client.default.connectTimeout=10000
feign.client.default.readTimeout=300000
Run Code Online (Sandbox Code Playgroud)
4)
feign.client.default.config.connectTimeout=10000
feign.client.default.config.readTimeout=300000
Run Code Online (Sandbox Code Playgroud)
错误堆栈跟踪是:
Error Message: feign.RetryableException: Read timed out executing GET http://myrequest...
Stacktrace:
feign.FeignException.errorExecuting(FeignException.java:67)
feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:10)
feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)
feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103)
Run Code Online (Sandbox Code Playgroud)
您能否建议我正确的配置或发现上面的代码块中有什么问题?
我正在使用 Spring Boot2.0.3.RELEASE和 openFeign:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
我在我的项目中声明了两个假客户端:
@FeignClient(name = "appleReceiptSandboxFeignClient",
url = "https://sandbox.itunes.apple.com",
configuration = Conf.class)
@RequestMapping(produces = "application/json", consumes = "application/json")
public interface AppleReceiptSandboxFeignClient {
@RequestMapping(value = "/verifyReceipt", method = RequestMethod.POST)
AppleReceiptResponseDTO sandboxVerifyReceipt(@RequestBody AppleReceiptRequestDTO dto);
}
Run Code Online (Sandbox Code Playgroud)
@FeignClient(name = "appleReceiptFeignClient",
url = "https://buy.itunes.apple.com")
@RequestMapping(produces = "application/json", consumes = "application/json")
public interface AppleReceiptFeignClient {
@RequestMapping(value = "/verifyReceipt", method = RequestMethod.POST)
AppleReceiptResponseDTO productionVerifyReceipt(@RequestBody AppleReceiptRequestDTO dto);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,即使基本网址和名称不同,似乎假客户端也会被视为冲突。
java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'com.myproject.central.client.AppleReceiptSandboxFeignClient' method
public abstract com.myproject.central.client.dto.AppleReceiptResponseDTO com.myproject.central.client.AppleReceiptSandboxFeignClient.sandboxVerifyReceipt(com.myproject.central.client.dto.AppleReceiptRequestDTO) …Run Code Online (Sandbox Code Playgroud) 我想使用@FeignClient(url=...)并使其直接转到给定的 url,而不是从功能区配置中获取主机。
我知道在 spring-cloud feign 中默认与ribbon和eureka一起出现。
根据这个:https : //cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-ribbon.html#spring-cloud-ribbon-without-eureka 可以禁用尤里卡并提供硬编码列表功能区的主机,例如:
${serviceId}:
ribbon:
listOfServers: ${host}
Run Code Online (Sandbox Code Playgroud)
根据这个:https : //cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html 可以为 feign 提供一个显式的 url,例如:
@FeignClient(name = "${feign.name}", url = "${feign.url}")
public interface StoreClient {
//..
}
Run Code Online (Sandbox Code Playgroud)
所以我对 FeignClient 到底会使用什么感到有些困惑:提供的 url 或来自功能区配置的主机?
我希望一些道具也可以禁用功能区以进行伪装,因为如果给 feign 一个单一的 url,那么负载平衡有什么意义?
Spring-cloud 发布火车 - Camden.SR2
我想通过 Spring-OpenFeign 从服务器下载一个文件并将其保存在本地目录中,并使用零拷贝。
简单的下载方法如下:
import org.apache.commons.io.FileUtils
@GetMapping("/api/v1/files")
ResponseEntity<byte[]> getFile(@RequestParam(value = "key") String key) {
ResponseEntity<byte[]> resp = getFile("filename.txt")
File fs = new File("/opt/test")
FileUtils.write(file, resp.getBody())
}
Run Code Online (Sandbox Code Playgroud)
在这段代码中,数据流将是这样的 feign Internal Stream -> Buffer -> ByteArray -> Buffer -> File
如何高效快速地下载和保存文件内存?
在测试伪装功能时低于异常。
*********************
应用程序无法启动
*********************
描述:
com.in28minutes.microservices.currencyconversionservice.CurrencyConversionController 中的字段currencyConversionServiceProxy 需要一个无法找到的“com.in28minutes.microservices.currencyconversionservice.CurrencyConversionServiceProxy”类型的bean。
注入点有以下注释:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
POM文件
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
....
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Run Code Online (Sandbox Code Playgroud)
货币转换服务应用程序.java
@SpringBootApplication
@EnableFeignClients …Run Code Online (Sandbox Code Playgroud) 问题:一个假客户端对 Spring boot Rest API 进行 API 调用,返回Page<T>无法反序列化sort该页面的属性。
com.fasterxml.jackson.databind.exc.InvalidDefinitionException:无法构造实例
org.springframework.data.domain.Sort(不存在创建者,如默认构造函数):无法从[来源:(BufferedReader);的对象值(不基于委托或基于属性的创建者)反序列化;行:1,列:238](通过参考链:org.springframework.cloud.openfeign.support.PageJacksonModule$SimplePageImpl["sort"])
不知道为什么注册PageJacksonModule似乎不支持这一点。
给定一个手动配置的 Feign 客户端:
public class TelematicsConfig {
private String host;
ObjectMapper provideObjectMapper() {
return new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setPropertyNamingStrategy(SnakeCaseStrategy.SNAKE_CASE)
.registerModule(new PageJacksonModule());
}
@Bean
TelematicsClient provideTelematicsClient() {
return Feign.builder()
.client(new OkHttpClient())
.encoder(new JacksonEncoder(provideObjectMapper()))
.decoder(new JacksonDecoder(provideObjectMapper()))
.logger(new Slf4jLogger(TelematicsClient.class))
.logLevel(Logger.Level.FULL)
.target(TelematicsClient.class, host);
}
}
Run Code Online (Sandbox Code Playgroud)
客户本身:
public interface TelematicsClient {
@RequestLine("GET /api/v1/telematics/devices")
Page<TelematicsDevice> getDevices();
}
Run Code Online (Sandbox Code Playgroud)
当调用这个我得到:
2020-09-16 12:38:49.707 ERROR 96244 --- …Run Code Online (Sandbox Code Playgroud) 我有一个 Feign 客户端测试,我想设置一个测试片,例如@WebMvcTest、@DataJpaTest等。
例如,以下测试使用@SpringBootTest并加载所有应用程序上下文:
@SpringBootTest
@AutoConfigureWireMock(port = 0)
class AgePredictorFeignClientTest {
@Autowired
private AgePredictorFeignClient agePredictorFeignClient;
@Test
void getAge() {
stubFor(get(urlEqualTo("/age-api?name=Henrique"))
.willReturn(aResponse().withBodyFile("25_years_old.json")
.withHeader("Content-Type", "application/json")));
Integer age = agePredictorFeignClient.getAge("Henrique").getAge();
assertThat(age).isEqualTo(25);
verify(getRequestedFor(urlEqualTo("/age-api?name=Henrique")));
}
}
Run Code Online (Sandbox Code Playgroud)
我如何更改此测试以仅加载与 Spring Cloud OpenFeign 相关的上下文?
此测试的应用程序的源代码位于https://github.com/henriquels25/openfeign-tests-sample。
我有一个现有的Spring Cloud Feign客户端界面,它为我的服务器端API提供了许多映射.我正在添加一些新方法,我突然遇到错误.我正在尝试添加表单的方法:
@RequestMapping(value = "/tasks/{id}", method = GET)
public Resource<Task> getTask(@PathVariable("id")Long id);
Run Code Online (Sandbox Code Playgroud)
一切都编译得很好,但是当我尝试调用上面的getTask()方法时,我总是得到一个IllegalArgumentException抱怨URL无效.这是真的,因为URL仍然包含UriTemplate {id}.
完整的堆栈是:
java.lang.IllegalArgumentException: Illegal character in path at index 29: http://connect/connect/tasks/{id}
at java.net.URI$Parser.fail(URI.java:2848)
at java.net.URI$Parser.checkChars(URI.java:3021)
at java.net.URI$Parser.parseHierarchical(URI.java:3105)
at java.net.URI$Parser.parse(URI.java:3053)
at java.net.URI.<init>(URI.java:588)
at java.net.URI.create(URI.java:850)
at feign.ribbon.RibbonClient.execute(RibbonClient.java:64)
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:92)
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:71)
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:94)
at com.sun.proxy.$Proxy55.getTask(Unknown Source)
Run Code Online (Sandbox Code Playgroud)
在同一个界面中有许多其他方法使用这种完全相同的模式,一切运行正常.我不能为我的生活找出为什么Feign/Spring突然出现这种方法的问题.我已经尝试了所有可能的设置组合和编写方法的方法.如果我只是删除了{id},那么调用将会通过,但显然会返回错误的数据,因为它缺少URI的id部分.
我正在使用Spring Cloud Angel.SR6和Spring Boot 1.2.8以及Feign 8.5.0.
现在,我将伪装与hystrix一起使用,事实证明,回退方法在5秒钟内调用20次后,Circuit将变为Open状态。如何更改此规则。例如,当回退方法在5秒钟内调用50次或以回退回调率调用时,让Circuit状态打开。这是我主要的Java代码。
ConsumerApplication.java
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
@RibbonClients({@RibbonClient(name = "cloud-provider", configuration = CloudProviderConfiguration.class)})
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
UserFeignClient.java
@FeignClient(name = "cloud-provider", fallback = UserFeignClient.HystrixClientFallback.class)
public interface UserFeignClient {
@RequestMapping("/{id}")
BaseResponse findByIdFeign(@RequestParam("id") Long id);
@RequestMapping("/add")
BaseResponse addUserFeign(UserVo userVo);
@Component
class HystrixClientFallback implements UserFeignClient {
private static final Logger LOGGER = LoggerFactory.getLogger(HystrixClientFallback.class);
@Override
public BaseResponse findByIdFeign(@RequestParam("id") Long id) {
BaseResponse response = new BaseResponse();
response.setMessage("disable!!!!");
return response;
}
@Override
public BaseResponse addUserFeign(UserVo userVo) …Run Code Online (Sandbox Code Playgroud) hystrix spring-cloud spring-cloud-feign spring-cloud-netflix
feign ×7
java ×6
spring-boot ×6
spring-cloud ×3
spring ×2
hystrix ×1
openfeign ×1
testing ×1
zero-copy ×1