小编ben*_*n c的帖子

Spring 启动 ClientHttpRequestInterceptor 在 401 上重新发送

所以我有下面的场景来实现使用Spring boot rest template消费REST-API(涉及令牌认证机制)。为了执行测试,我在 Spring Boot 中创建了简单的模拟 REST API。这是过程,

从我的 API 消费者应用程序中,

  • 使用rest-template受保护的 API发送请求,此 API 要求Authorization: Bearer <token>请求中存在标头。
  • 如果此令牌有问题(缺少标头、无效令牌),受保护的 API 将返回HTTP-Unauthorized (401).
  • 发生这种情况时,消费者 API 应该向另一个受保护的 API 发送另一个请求,该 API 返回有效的访问令牌,此受保护的 API 需要Authorization: Basic <token>存在标头。新的访问令牌将存储在静态字段中,并将用于所有其他请求进行身份验证。

这可以通过简单的捕捉来实现401-HttpClientErrorExceptionRestTemplate消费方式(postForObject),但这个想法是从分离它REST-API的消费类。为了实现它,我尝试使用ClientHttpRequestInterceptor

这是我到目前为止尝试过的代码。

拦截器类

public class AuthRequestInterceptor implements ClientHttpRequestInterceptor {

private static final Logger LOGGER = LoggerFactory.getLogger(AuthRequestInterceptor.class);
private static final String BASIC_AUTH_HEADER_PREFIX = "Basic ";
private static …
Run Code Online (Sandbox Code Playgroud)

java spring interceptor access-token spring-boot

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

具有消费者-生产者设计“超出 CPU 时间限制”的 TCP 套接字服务器

这个问题是在运行使用消费者/生产者设计创建的套接字服务器时出现的,程序cpu time limit exceeded因日志错误而崩溃。我还发现cpu使用量比当时更多90%。这是服务器的代码,它可能出了什么问题,我该如何优化它?

我使用这种queue方法来避免threads为每个请求创建如此多的请求。

在主方法中(主线程)

//holds socket instances
ConcurrentLinkedQueue<Socket> queue = new ConcurrentLinkedQueue<>();

//create producer thread
Thread producer = new Thread(new RequestProducer(queue));
//create consumer thread
Thread consumer = new Thread(new RequestConsumer(queue));

producer.start();
consumer.start();
Run Code Online (Sandbox Code Playgroud)

请求生产者线程

//this holds queue instance coming from main thread
ConcurrentLinkedQueue<Socket> queue

//constructor, initiate queue
public RequestProducer(
    ConcurrentLinkedQueue<Socket> queue
) {
    this.queue = queue;
}

public void run() {
    try {
        //create serversocket instance on port 19029 …
Run Code Online (Sandbox Code Playgroud)

java sockets concurrency multithreading producer-consumer

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