我正在尝试比较同一类的两个对象,目标是比较它们并确定哪些字段不匹配。
我的域类示例
@Builder(toBuilder=true)
class Employee {
String name;
int age;
boolean fullTimeEmployee;
}
Run Code Online (Sandbox Code Playgroud)
两个对象
Employee emp1 = Employee.builder().name("john").age(25).fullTime(false).build();
Employee emp2 = Employee.builder().name("Doe").age(25).fullTime(true).build();
Run Code Online (Sandbox Code Playgroud)
比较两个对象
int result = Comparator.comparing(Employee::getName, Comparator.nullsFirst(Comparator.naturalOrder()))
.thenComparing(Employee::getAge, Comparator.nullsFirst(Comparator.naturalOrder()))
.thenComparing(Employee::isFullTimeEmployee, Comparator.nullsFirst(Comparator.naturalOrder()))
.compare(emp1, emp2);
Run Code Online (Sandbox Code Playgroud)
结果将是0因为name&fullTime字段彼此不匹配。
但我也想生成一个不匹配的字段列表......如下所示
List<String> unmatchedFields = ["name","fulltimeEmployee"];
Run Code Online (Sandbox Code Playgroud)
我可以用更好的方式来做,而不是一堆 if() else
When uploading a csv file and a JSON object at the following endpoint
@PostMapping(value = "dataset/rows/query", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Mono<List<Integer>> getRowsByQuery(@RequestPart("dataset") Mono<FilePart> file,
@RequestPart("query") QueryDTO query){
return Mono.just(new ArrayList<>());
}
Run Code Online (Sandbox Code Playgroud)
I get the following error:
2020-12-17 12:25:05.142 ERROR 195281 --- [or-http-epoll-3] a.w.r.e.AbstractErrorWebExceptionHandler : [d418565e-17] 500 Server Error for HTTP POST "/dataset/rows/query"
org.springframework.core.io.buffer.DataBufferLimitException: Part headers exceeded the memory usage limit of 8192 bytes
at org.springframework.http.codec.multipart.MultipartParser$HeadersState.onNext(MultipartParser.java:360) ~[spring-web-5.3.1.jar:5.3.1]
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ? org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter [DefaultWebFilterChain] …Run Code Online (Sandbox Code Playgroud) 在我的请求处理程序中,如果传入的内容accountId无法转换为有效的,ObjectId我想捕获错误并发回有意义的消息;但是,这样做会导致返回类型不兼容,并且我无法弄清楚如何实现这个非常简单的用例。
我的代码:
@GetMapping("/{accountId}")
public Mono<ResponseEntity<Account>> get(@PathVariable String accountId) {
log.debug(GETTING_DATA_FOR_ACCOUNT, accountId);
try {
ObjectId id = new ObjectId(accountId);
return repository.findById(id)
.map(ResponseEntity::ok)
.switchIfEmpty(Mono.just(ResponseEntity.notFound().build()));
} catch (IllegalArgumentException ex) {
log.error(MALFORMED_OBJECT_ID, accountId);
// TODO(marco): find a way to return the custom error message. This seems to be currently
// impossible with the Reactive API, as using body(message) changes the return type to
// be incompatible (and Mono<ResponseEntity<?>> does not seem to cut it).
return Mono.just(ResponseEntity.badRequest().build());
}
}
Run Code Online (Sandbox Code Playgroud)
该body(T …
我出现以下错误:
Exception: Error creating bean with name 'inventoryService' defined in URL [jar:file:/app.jar!/BOOT-INF/classes!/com/epi/services/inventory/items/InventoryService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itemRepository': Cannot resolve reference to bean 'databaseClient' while setting bean property 'databaseClient'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'databaseClient' available
2019-06-18 18:38:41,409 INFO [main] org.apache.juli.logging.DirectJDKLog: Stopping service [Tomcat]
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.catalina.loader.WebappClassLoaderBase (jar:file:/app.jar!/BOOT-INF/lib/tomcat-embed-core-8.5.29.jar!/) to field java.lang.Thread.threadLocals
WARNING: Please consider reporting this …Run Code Online (Sandbox Code Playgroud) 我准备了一堆要并行发送到外部 Web 服务的请求。在此流程中,我继续直接处理响应(例如,将某些内容插入数据库)。
问题:我想跟踪最大请求时间(针对一个请求!),不包括处理。但正如所写,这只会跟踪全局时间,包括任何子进程:
StopWatch watch = new StopWatch();
watch.start();
Flux.fromIterable(requests)
.flatMap(req -> webClient.send(req, MyResponse.class)
.doOnSuccess(rsp -> processResponse(rsp))) //assume some longer routine
.collectList()
.block();
watch.stop();
System.out.println(w.getTotalTimeMillis());
Run Code Online (Sandbox Code Playgroud)
问题:如何测量请求花费的最长时间(不包括processResponse()时间)?
public Mono<ServerResponse> getMessage(ServerRequest request) {
//this call returns Mono<ApiClientResponse>
return apiClient.hystrixWrappedGetMessages(request.headers().asHttpHeaders(), request.queryParams())
.switchIfEmpty(/* Here */)
}
Run Code Online (Sandbox Code Playgroud)
请原谅代码稍微不完整,当我遇到这个问题时,我正在重组它。要点是 /* Here */ 在调用中switchIfEmpty(),编译器强制使用类型Mono<ApiClientResponse>,但是当hystrixWrappedGetMessages()返回时Mono.empty()我想通过返回 204 来处理它Mono<ServerResponse>,否则我想返回 200。我怎样才能做到这一点?
理想情况下,我可以在地图调用中检查它是否是 Mono.empty() ,但如果它是空的 Mono,它似乎不会输入地图。考虑过使用可选选项,但它们似乎与 Monos 不能很好地配合。
java reactive-programming reactor-netty spring-webflux spring-webclient
我正在使用 Spring boot Webflux 2.4.4(最新)并尝试使用 WebClient 调用后端 URL。WebClient 总是响应超过 20 秒。如果我直接点击 URL,它会以毫秒为单位响应。
Pom 看起来如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Run Code Online (Sandbox Code Playgroud)
代码如下所示:
@RestController
public class Controller {
@GetMapping("/test")
public Mono<String> test() {
long startMillis = System.currentTimeMillis();
return webClient().get().uri("https://www.google.com").exchangeToMono(response -> {
System.out.println("Elapsed Time is: " + (System.currentTimeMillis() - startMillis));
if (response.statusCode().equals(HttpStatus.OK)) {
return Mono.just("OK");
}
return Mono.just("OK");
});
}
private WebClient webClient() {
return WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(HttpClient
.create().secure().responseTimeout(Duration.ofMillis(1000))
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000).doOnConnected(c -> c …Run Code Online (Sandbox Code Playgroud) 据我了解,此注释用于在控制器中获取经过身份验证的用户。但我可以通过以下代码获得没有它的用户:
@GetMapping("/example")
public String currentUserName(Authentication authentication) {
return authentication.getName();
}
Run Code Online (Sandbox Code Playgroud)
如果您能告诉我它有什么用或分享一些文档,我将不胜感激,因为我找不到。我非常感谢你的帮助!
所以开始一个新项目,我想使用 r2dbc 和 webflux,一直在研究处理数据库迁移的支持。我在这里找到的最后一个答案是从 2019 年 7 月开始,liquibase 不支持 R2DBC,在谷歌搜索之后,情况似乎仍然如此。
梦想是r2dbc-h2在本地开发时使用,然后在生产中使用类似 postgres 的东西。Liquibase 将在本地和生产中管理表结构。
一直试图在谷歌上搜索一下这种设置的样子,但那里的信息很少。
我一直在考虑使用 设置表格liquibase-maven-plugin,但我不知道这是否适用于r2dbc-h2.
所以几个问题:
这对我来说是一个非常黑洞,有任何信息吗?
我仍在尝试了解 reactor map() 和 flatMap() 方法之间的区别。首先我查看了 API,但它并没有真正的帮助,它让我更加困惑。然后我用谷歌搜索了很多,但似乎没有人有一个例子来使差异变得可以理解,如果有任何差异的话。
因此,我尝试编写两个测试来查看每种方法的不同行为。但不幸的是它并没有像我希望的那样工作......
第一个测试方法是测试反应式 flatMap() 方法:
@Test
void fluxFlatMapTest() {
Flux.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.window(2)
.flatMap(fluxOfInts -> fluxOfInts.map(this::processNumber).subscribeOn(Schedulers.parallel()))
.doOnNext(System.out::println)
.subscribe();
}
Run Code Online (Sandbox Code Playgroud)
输出符合预期,可解释,如下所示:
9 - parallel-2
1 - parallel-1
4 - parallel-1
25 - parallel-3
36 - parallel-3
49 - parallel-4
64 - parallel-4
81 - parallel-5
100 - parallel-5
16 - parallel-2
Run Code Online (Sandbox Code Playgroud)
第二种方法应该测试 map() 方法的输出,以与 flatMap() 方法的上述结果进行比较。
@Test
void fluxMapTest() {
final int start = 1;
final int stop …Run Code Online (Sandbox Code Playgroud) 我有一个排序问题.
假设我有4个字符串存储在数组中,其中我想要成对生成所有组合.并且从这些对中对它们进行排序,使得没有2个阵列位置在最大可能的范围内彼此相继
例:
String[] array = {"one", "two", "three", "four"};
// want to generate
one - two
one - three
one - four
two - three
two - four
three - four
// then sort
one - two
three - four
one - four
two - three //two "three" after each other
one - three
two - four
Run Code Online (Sandbox Code Playgroud)
(在这种情况下相互得到2的那个"three"在排序时也是随机的)
我不知道如何用Java做到这一点.尝试嵌套for循环,有些人告诉我递归循环.我不想要:
" 只需复制粘贴此代码,一切都会正常工作 "我真的很想了解如何写这样的东西.
我该如何处理这个问题?
java ×10
spring-boot ×4
netty ×2
r2dbc ×2
spring ×2
arrays ×1
comparator ×1
java-8 ×1
liquibase ×1
loops ×1
postgresql ×1
recursion ×1
sorting ×1