除非在调试模式下,否则永远不会触及新线程中自动连接的@Resource

时间:2017-05-15 02:51:17

标签: java spring multithreading rest spring-boot

我正在编写一个Spring-boot应用程序,它有一个我的前端会话的REST控制器。当我调用控制器时,它会在队列中插入一个名称。下面的处理器检查incomingQueue并使用队列中的最新名称对数据库执行操作。

这是我完全难过的地方。当我在eclipse中处于调试模式时,我的代码工作,但是当我只是运行应用程序时,下面的代码永远不会触及队列。没有来自System.out.println(name + " removed from queue. Queue size now: " + incomingQueue.size());行的输出。

为什么会这样?

REST控制器:

@Resource
Queue<String> incomingQueue;

@RequestMapping(value="/simpleAction",method=RequestMethod.GET)
public @ResponseBody int queueName(@RequestParam(value="name", required=true) String name) throws RiotApiException {
    incomingQueue.add(name);
    return incomingQueue.size();
}

请求处理器:

@Component
public class RequestProcessor implements Runnable {

@Resource
Queue<String> incomingQueue;

@Autowired
private WebApplicationContext context;

public SimpleAction getSimpleAction() {
    return (SimpleAction) context.getBean("simpleAction");
}


public void run(){
    System.out.println("Spawning Request Processor");

    while (true) {
        if (!incomingQueue.isEmpty()) {
            String name = incomingQueue.remove();
            System.out.println(name + " removed from queue. Queue size now: " + incomingQueue.size());
            new Thread(new Runnable() {
                 public void run() {
                     getSimpleAction().performAction(name);
                 }
            }).start();
        }
    }
  }
}

修改

我如何启动请求处理器:

@Component
public class ApplicationLoader implements CommandLineRunner {

    @Autowired
    RequestProcessor requestProcessor;

    @Override
    public void run(String... strings) throws Exception {

        new Thread(requestProcessor).start();
    }
}

0 个答案:

没有答案