我正面临与WebClient和的问题reactor-extra。确实,我有以下方法:
public Employee getEmployee(String employeeId) {
return webClient.get()
.uri(FIND_EMPLOYEE_BY_ID_URL, employeeId)
.retrieve()
.onStatus(HttpStatus.NOT_FOUND::equals, clientResponse -> Mono.empty())
.onStatus(HttpStatus::is5xxServerError, clientResponse -> Mono.error(new MyCustomException("Something went wrong calling getEmployeeById")))
.bodyToMono(Employee.class)
.retryWhen(Retry.onlyIf(ConnectTimeoutException.class)
.fixedBackoff(Duration.ofSeconds(10))
.retryMax(3))
.block();
}
Run Code Online (Sandbox Code Playgroud)
我发现我可以使用,retryWhen(Retry.onlyIf(...))因为我只想在ConnectTimeoutException抛出a 时重试。我从这篇文章中找到了这个解决方案:spring webclient: retry with backoff on specific error
但是,在reactor以下方法的最新版本中已弃用:
public final Mono<T> retryWhen(Function<Flux<Throwable>, ? extends Publisher<?>> whenFactory)
谷歌搜索后,我还没有发现任何解决这个问题的时间:是否有任何替代retryWhen和Retry.onlyIf使用的最新版本reactor
谢谢你的帮助 !
reactive-programming spring-boot project-reactor reactor-netty spring-webclient
经过数小时的研究,我找不到解决问题的方法。我有一个Map<String, List<User>>,我想根据列表中的某些值删除地图上的某些项目。
我必须跟随User类
public class User {
public String firstName,
public Integer age
public boolean is50() {
return this.age.equals(50);
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个这样的地图:
Map<String, List<User> myMap = new HashMap<>();
myMap.put("A", new ArrayList<>());
myMap.get("A").add(new User("John", 50));
myMap.get("A").add(new User("Bob", 30));
myMap.put("B", new ArrayList<>());
myMap.get("B").add(new User("Sam", 25));
myMap.get("B").add(new User("Sarah", 56));
myMap.put("C", new ArrayList<>());
myMap.get("C").add(new User("Gill", 15));
myMap.get("C").add(new User("Jim", 20));
Run Code Online (Sandbox Code Playgroud)
现在,如果列表年龄中至少有一个用户为50,我想删除Map的条目。而且,我想使用Java 8功能来实现这一点。
我发现有一个removeIf功能,但不能使其与列表一起使用。
我已经尝试过这样的事情:
Map<String, List<User> filteredMap = myMap
.enrySet()
.removeIf(e -> e.getValue()
.stream()
.filter(user -> user::is50)
.collect(Collectors.toList())
Run Code Online (Sandbox Code Playgroud)
当然那是行不通的:(
例外的输出是一个过滤的地图,所有用户只有B和C键(必须删除A键,因为John有50岁了)
谢谢您的帮助,希望一切都清楚;)
我不知道如何解决 Spring Boot 中的以下用例。事实上,我有一个 Spring Boot Rest Api(例如:),user-api具有以下控制器方法和参数的自定义验证器:
@PostMapping
public User createUser(@ValidZipCode @RequestBody @Valid User user){
return userService.saveUser(user);
}
Run Code Online (Sandbox Code Playgroud)
该类User是在外部依赖项中定义的(例如:user-model)。它有以下字段:
public class User {
@NotNull
private String firstName;
@NotNull
private String lastName;
private String zipCode;
// getters, setters ..
}
Run Code Online (Sandbox Code Playgroud)
在中,user-api我创建了以下自定义注释:
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ZipCodeValidator.class)
public @interface ValidZipCode {
String message() default "Must be a valid zipCode. Found: ${validatedValue}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Run Code Online (Sandbox Code Playgroud)
所以 …
我一直在寻找以下用例的解决方案但没有成功,我希望有人可以提供帮助:
假设以下用例。我需要调用客户 Api( customerApi),而该 api 需要一个Bearer令牌,当我调用时该令牌可能已过期customerApi。如果令牌已过期,则customerApi返回401响应。
我想做的是,如果我收到一个401并调用该方法来获取新Bearer令牌,则仅重试一次。如果重试仍然返回401,我需要抛出一个Exception
获取token的方法Bearer:
private String getToken() {
return oAuthService.getToken();
}
Run Code Online (Sandbox Code Playgroud)
webClient调用customerApi(customerWebClient是用 ) 创建的 bean 的用法WebClient.Builder:
public Customer getCustomerById(String customerId, String token) {
return customerWebClient.get()
.uri("myurl/customers/{customerId}, customerId)
.headers(httpHeaders -> {
httpHeaders.add(HttpHeaders.AUTHORIZATION, "Bearer " + token);
})
.retrieve()
.bodyToMono(Customer.class)
.onErrorResume(WebClientResponseException.NotFound.class, notFound ->
Mono.error(new MyCustomException()))
.block();
}
Run Code Online (Sandbox Code Playgroud)
看来retryWhen只能用超时来升级了。所以我希望有人知道如何实现这个用例^^
感谢您的帮助 :)
编辑 …
首先,重要的是要指定应用程序已经部署并且我们的 spring 安全配置有效。如果未经身份验证的用户尝试访问 API 的任何端点,则会返回 401 Unauthorized。
@WebMvcTest接下来,在这个示例示例中,我想使用和 来测试控制器spring security
@WebMvcTest(EmployeeController.class)
@Import(SecurityConfig.class)
class EmployeeControllerTest {
@Autowired
private WebApplicationContext ctx;
protected MockMvc mvc;
@MockBean
private EmployeeService service;
@BeforeEach
public void setUp() {
this.mvc = MockMvcBuilders
.webAppContextSetup(ctx)
.apply(springSecurity())
.build();
}
@Test
void unauthorized_role_should_return_401() {
mvc.perform(get("/employees/1").accept(MediaType.APPLICATION_JSON)
.with(SecurityMockMvcRequestPostProcessors.user("manager").roles("UNKNOWN")))
.andExpect(status().isUnauthorized())
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码有效,但我不明白为什么需要将该SecurityConfig类导入到测试类中。事实上,如果我删除@Import,mockMvc返回 200。但是,我发现的每个示例项目都Github只是使用@WebMvcTest,即使该项目有一个SecurityConfig类
我正在为异步等待功能的循环而苦苦挣扎。我正在创建一个向另一个 API 发送请求的 API。我必须做一个循环,因为用户可以一次在数据库中插入许多项目。
我调用的 API 拒绝并行执行,所以我不能使用Promise.all:/
为了实现该服务,我创建了一个函数来插入一个对象:
const addValue = async (ID:number, cookie: string) => {
try {
const addValueBody = await addValueQuery(ID:number)
const header = { 'cookie': cookie, 'content-type': 'application/json' }
const fetchResult = fetch('http://api-to-call.xyz', { method: `POST`, headers: header, body: addValueBody })
const response = await fetchResult
const jsonData = await response.json()
return jsonData
} catch (e) {
throw Error(e.message)
}
}
Run Code Online (Sandbox Code Playgroud)
还有一个将addValue在 for 循环内执行的函数:
const addMulti = async (values: any, cookie: string) …Run Code Online (Sandbox Code Playgroud) 我需要将 a 转换dto为entity,并且entity有一个要填充的字段,该字段不需要 的任何字段dto。事实上,该@Mapping注释没有任何来源。
让我们用这个简单的例子来说明它:
public class Employee {
private String firstName;
private String customId;
}
public class EmployeeDto {
private String firstName;
}
Run Code Online (Sandbox Code Playgroud)
customId如您所知,实体的字段Employee不存在于EmployeeDTO.
另外,我还有以下内容formatter。显然,我创建了一个@CustomIdGenerator @interface
public class EmployeeFormatter {
@CustomIdGenerator
public static String simulationIdGenerator() {
return // businessLogic
}
}
Run Code Online (Sandbox Code Playgroud)
最后我的映射器看起来像这样:
@Mapper(uses = EmployeeFormatter.class)
public abstract class EmployeeMapper {
@Mapping(target = "customId", qualifiedBy = customIdGenerator.class)
public abstract Employee toEmployee(EmployeeDTO dto); …Run Code Online (Sandbox Code Playgroud) 我在使用Elasticsearch查询时遇到了一些麻烦。(我使用elasticsearch 5)。我想结合必须布尔查询和应该为了创建一个符合此条件的查询:
Get users which match (city = x) AND (school = y) AND (age = 12) AND (team = a OR b)
Run Code Online (Sandbox Code Playgroud)
我尝试了许多查询,但仍然有格式错误的查询异常。
{
"query": {
"bool": {
"must" : [
{
"match": {
"city": "x"
}
},
{
"match" : {
"school" : "y"
}
},
{
"match" : {
"age" : 12
},
"bool": {
"should": [
{"term": {"team": "A"}},
{"term": {"team": "B"}}
]
}
}
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望有人可以帮助我:D
谢谢你的帮助
spring-boot ×3
java ×2
async-await ×1
java-stream ×1
javascript ×1
loops ×1
mapstruct ×1
mockmvc ×1
node.js ×1
typescript ×1