小编use*_*406的帖子

开玩笑:不使用现代计时器时 setSystemTime 不可用

这是代码。TypeError: setSystemTime is not available when not using modern timers当我运行测试时出现错误。我"@jest/fake-timers": "^27.4.2"在我的 package.json 中,因为我认为某些依赖项中的包可能存在冲突,但问题仍然存在

beforeAll(() => {
    jest.useFakeTimers('modern');
    jest.setSystemTime(new Date());
});

afterAll(() => {
    jest.useRealTimers();
});
Run Code Online (Sandbox Code Playgroud)

知道如何解决这个问题吗?

jestjs

10
推荐指数
1
解决办法
1万
查看次数

Spring Boot 3 与微米级跟踪和处理 Traceparent 标头相关的问题

我有下面的代码,用于处理来自其他应用程序的请求,这些应用程序通过标头传递traceId Traceparent。我希望它能够从请求中吸收父级 TraceId,并且在 zipkin 仪表板中我应该看到该应用程序与其他应用程序之间的连接。它曾经与spring-cloud-sleuth-zipkin. 现在我迁移到spring boot 3,包改为micrometer-tracing-bridge-otel(参见pom.xml)。现在,它不再从请求中提取父traceId,而是生成一个全为0的默认父traceId,导致应用程序与zipkin仪表板中的其他应用程序断开连接

我使用带有标头的简单卷曲请求进行了测试Traceparentcurl --location --request GET 'http://localhost:8080/test' --header 'Traceparent: 00-63cf0173620c57b0aed605ee94255089-1444ca74c3d2133a-01'但此代码不会从标头中提取父上下文。知道如何进行这项工作吗?

@RestController
public class Test {

    @Autowired
    private Tracer tracer;

    @GetMapping(path="/test")
    public ResponseEntity<?> handleTest() {
        ScopedSpan span = tracer.startScopedSpan("test span");
        return ResponseEntity.ok();
    }
}

Run Code Online (Sandbox Code Playgroud)

pom.xml

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.2</version>
    </parent>

        <dependency>
            <groupId>io.micrometer</groupId>
            <artifactId>micrometer-tracing-bridge-otel</artifactId>
        </dependency>
        <dependency>
            <groupId>io.opentelemetry</groupId>
            <artifactId>opentelemetry-exporter-zipkin</artifactId>
        </dependency>
        <dependency>
            <groupId>io.zipkin.reporter2</groupId>
            <artifactId>zipkin-sender-urlconnection</artifactId>
        </dependency>

Run Code Online (Sandbox Code Playgroud)

spring-boot spring-cloud-sleuth micrometer spring-micrometer micrometer-tracing

9
推荐指数
1
解决办法
6418
查看次数

Spring 4 WebSocket + sockJS:在跟踪中找不到"找不到匹配的方法",并且未调用@MessageMapping处理程序

控制器代码:

@Controller
public class SockController {

    @MessageMapping(value="/chat")
    public void chatReveived(Message message, Principal principal) {
        ...
        LOGGER.debug("chatReveived message [{}]", message);
        ...  
    }
}
Run Code Online (Sandbox Code Playgroud)

WebSocketConfig:

@Configuration
@EnableWebSocketMessageBroker
@EnableScheduling
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/queue/", "/topic/");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/portfolio").withSockJS();
    }
}
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

        var socket = new SockJS('/portfolio');
        var stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame) {
            ...
        });
        stompClient.send("/app/chat", {}, JSON.stringify(message))
Run Code Online (Sandbox Code Playgroud)

使用这些代码,前端能够通过WebSocket与服务器连接并发送消息.但@MessageMapping处理程序方法chatReveived()不会被调用.

前端输出:

Opening Web Socket...
Web Socket Opened...
>>> CONNECT
accept-version:1.1,1.0 …
Run Code Online (Sandbox Code Playgroud)

spring stomp websocket sockjs spring-4

7
推荐指数
1
解决办法
1454
查看次数

在Webflux WebFilter的最后执行一些逻辑

在传统的 Spring MVC 过滤器中,我可以在后面添加一些代码,chain.doFilter以便它们在最后执行。例如:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
   chain.doFilter(request, response);
   A();
}
Run Code Online (Sandbox Code Playgroud)

该函数A将在所有过滤器和控制器执行之后,甚至在onBeforeCommitResponse调用之后,在最后执行。

我想在 WebFlux 中做同样的事情WebFilter

public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    return chain.filter(exchange);
    // Call A() after all filters, controllers and after beforeCommit
}
Run Code Online (Sandbox Code Playgroud)

我该如何实现这一目标?

spring spring-boot spring-webflux

7
推荐指数
1
解决办法
1488
查看次数

@ConditionalOnProperty 检查前缀是否存在

我有这个 application.yml 文件

 db1: 
   url: ...
 db2:
   url: ... 
Run Code Online (Sandbox Code Playgroud)

我想在 db1 配置存在时创建一个 bean,否则什么也不做。这是我尝试过的:

@Bean
@ConditionalOnProperty(prefix = "db1") // this throw error that name or value must be specified
@ConfigurationProperties(prefix = "db1")
public DB getDB1() {
   ...
}

Run Code Online (Sandbox Code Playgroud)

如何才能在属性文件中存在前缀时创建 bean?

spring spring-boot

6
推荐指数
1
解决办法
2241
查看次数

Spring @Bean(name ="name") vs @Bean @Qualifier("name")

以下2个bean声明之间有什么区别吗?

 @Bean(name = "bean1")
 public A getA() {
     return new A();
 }


 @Bean
 @Qualifier("bean1")
 public A getA() {
     return new A();
 }
Run Code Online (Sandbox Code Playgroud)

两者都可以使用自动装配 @Qualifier

 @Autowire
 public void test(@Qualifier("bean1") A a) {
     ...
 }
Run Code Online (Sandbox Code Playgroud)

spring spring-boot

5
推荐指数
2
解决办法
3825
查看次数

通过 Spring Webflux 中的请求生命周期共享数据

在 Spring MVC 中我可以使用 ThreadLocal 通过一个请求在不同的组件之间共享数据,当请求完成时数据会被自动清除。使用 WebFlux,由于一个请求可以由多个线程处理,因此该解决方案将不起作用。如何实现类似的解决方案,以便最初 WebFilter 可以在请求上下文中设置一些数据,然后可以在控制器中访问和修改数据,以及请求经过的任何事件处理程序?

我尝试了subscriberContext,但没有用。这是我的代码。为什么这不起作用?还有其他方法可以共享数据吗?

public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    exchange.getResponse().beforeCommit(() -> {
        return Mono.subscriberContext()
         .map(context -> {
              context.hasKey("test"); // this returns false
         })
    }

    return Mono.subscriberContext()
        .map(context -> {context.put("test", "test");})
        .flatMap(chain.filter(exchange))
}
Run Code Online (Sandbox Code Playgroud)

spring spring-boot spring-webflux

5
推荐指数
1
解决办法
460
查看次数

cert-manager:没有配置的挑战解决程序可以用于此挑战

我按照此说明在我的 EKS 集群https://cert-manager.io/docs/tutorials/acme/ingress/上设置了一个证书管理器。

这是我的入口

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: test
  annotations:
    kubernetes.io/ingress.class: "nginx"
    cert-manager.io/issuer: "letsencrypt-staging"
spec:
  tls:
  - hosts:
      - '*.test.com'
    secretName: test-tls
  rules:
    - http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: test-service
                port:
                  number: 80
Run Code Online (Sandbox Code Playgroud)

这里是发行人。我刚刚从说明中复制了配置

apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
  name: letsencrypt-staging
spec:
  acme:
    server: https://acme-staging-v02.api.letsencrypt.org/directory
    email: info@test.com
    privateKeySecretRef:
      name: letsencrypt-staging
    solvers:
      - http01:
          ingress:
            class: nginx
Run Code Online (Sandbox Code Playgroud)

部署后发现证书就绪状态为false

kubectl get certificate
NAME          READY   SECRET        AGE
test-tls   False   test-tls   2m45s
Run Code Online (Sandbox Code Playgroud)

然后我按照此进行故障排除https://cert-manager.io/docs/faq/troubleshooting/

我跑了kubectl …

kubernetes lets-encrypt cert-manager amazon-eks

5
推荐指数
1
解决办法
8066
查看次数

从 Mono.fromCallable 返回 Mono.empty()

我想做如下的事情。在 Mono.fromCallable 中,我运行一些块逻辑,然后根据值返回 Mono.empty() 或该值,以便它将触发映射或 defaultIfEmpty。

            Mono.fromCallable(() -> {
                double number = Math.random();
                if (number < 0.5) {
                    return Mono.empty();
                }

                return number;
            })
            .map(number -> 1)
            .defaultIfEmpty(0)
Run Code Online (Sandbox Code Playgroud)

这会产生错误,因为 Mono.fromCallable 期望一致的返回值。如何调整代码以使其正常工作?

project-reactor spring-webflux

4
推荐指数
1
解决办法
2507
查看次数

AtomicReference getAndUpdate 的混乱

我对 AtomicReference 如何保证原子性有点困惑getAndUpdate。考虑以下示例

示例1

AtomicReference<Set<String>> set = new AtomicReference<>(new HashSet<>());
set.getAndUpdate(current -> {
    Set<String> updated = new HashSet<>();
    updated.add("test");
    return updated;
});
Run Code Online (Sandbox Code Playgroud)

示例2

AtomicReference<Set<String>> set = new AtomicReference<>(new HashSet<>());
set.getAndUpdate(current -> {
    current.add("test");
    return current;
});
Run Code Online (Sandbox Code Playgroud)

在示例 2 中,该集合将在 的回调中被修改getAndUpdate。如果多个线程尝试同时访问此函数,它们是否会看到修改后的状态,或者getAndUpdate通过在将原始集传递给回调时克隆原始集来防止这种情况发生,以便在一个线程中发生的修改不会在其他线程中看到?如果示例 2 不能保证原子性,为什么允许getAndUpdate我们编写这段代码?

示例 1 将保证原子性,因为修改发生在新集合上。但它如何从下面推迟呢?

AtomicReference<Set<String>> set = new AtomicReference<>(new HashSet<>());
Set<String> updated = new HashSet<>();
updated.add("test");
set.set(updated);
Run Code Online (Sandbox Code Playgroud)

java

1
推荐指数
1
解决办法
1312
查看次数