简体   繁体   English

Java Spring bean创建另一个bean的更多实例

[英]Java Spring bean that create more instances of another bean

I have this situation: 我有这种情况:

@RestController
@RequestMapping("/api")
public class A {

    @Autowired
    private B b;

    @RequestMapping(value = "/exec", method = RequestMethod.GET)
    public void execute(){
        int i = 0;
        for (i; i < 10; i++;){
            b.execute(i);
        }
    }

    @RequestMapping(value = "/exec/{i}", method = RequestMethod.GET)
    public void executeSingle(@PathVariable int i) {
        b.execute(i);
    }
}

@Service
public class B{
    public void execute(int i){
        //...a long time...
    }
}

Now I call method execute() of A and it takes long time because it call B.execute() consecutively. 现在,我调用方法A的execute(),因为它连续调用B.execute(),所以需要很长时间。

I would like to have a parallel approach. 我想有一个并行的方法。

I would create multiple instances of bean B and call them at the same time, so I can gain about 9/10 of the time I spent with the actual "loop solution". 我将创建多个bean B实例并同时调用它们,因此我可以获得实际“循环解决方案”所花费时间的9/10。

How can I do that? 我怎样才能做到这一点?

Now to get these improvements I call 10 times method executeSingle(int i) of A, via browser with multiple HTTP GET like: 现在要获得这些改进,我通过具有多个HTTP GET的浏览器调用了A的10倍方法executeSingle(int i):

GET ADDRESS/api/exec/1 获取地址/ api / exec / 1

GET ADDRESS/api/exec/2 获取地址/ api / exec / 2

GET ADDRESS/api/exec/3 获取地址/ api / exec / 3

... ...

But I would like to use a more elegant solution. 但是我想使用一个更优雅的解决方案。

I would say that you need to use ExecutorService and in particular ThreadPoolExecutor Read about them to see how to use it. 我要说的是,您需要使用ExecutorService ,尤其是ThreadPoolExecutor。请阅读有关它们的内容,以了解如何使用它。 Then I would do the following changes to your code: change your B class to implement Runnable. 然后,我将对您的代码进行以下更改:更改您的B类以实现Runnable。

    public class B implements Runnable {
      private int myParam;

      public void setMyParam(int i) {
        myParam = i;
      }

    public void run() {
      execute(myParam)
    }

    private void execute(int i) {
      ...
    }
  }

Now don't make it a bean and don't inject it into your A class. 现在,不要将其制成bean,也不要将其注入您的A类中。 But make a BclassFactory class that creates and returns a B class (or just create a new B class every time you need it. Now inject into your A class an instance of ThreadPoolExecutor and in your execute method do something like this: 但是创建一个BclassFactory类来创建并返回一个B类(或者在每次需要时都创建一个新的B类。现在,将一个ThreadPoolExecutor实例注入到A类中,然后在您的execute方法中执行以下操作:

   @RequestMapping(value = "/exec", method = RequestMethod.GET)
public void execute(){
    int i = 0;
    for (i; i < 10; i++;){
        B b = factory.getB();
        b.setMyParameter(i);
        executor.submit(b);
    }
}

That should do the trick 这应该够了吧

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM