Web应用程序中的Spring线程


问题内容

我正在为MMO浏览器游戏编写服务器,并且我需要创建几个线程。他们将一直运行,并需要一些睡眠时间。这样使用弹簧螺纹是个好主意吗?

@Component
@Scope("prototype")
public class PrintTask2 implements Runnable{

String name;

public void setName(String name){
    this.name = name;
}

@Override
public void run() {

    System.out.println(name + " is running");

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(name + " is running");

}

}

与作为豆实现的任务执行器?

<bean id="taskExecutor"
       class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="5" />
    <property name="maxPoolSize" value="10" />
    <property name="WaitForTasksToCompleteOnShutdown" value="true" />
</bean>

同样,线程在也定义为bean的单例中启动。

我的方法有什么问题?


问题答案:

您可以用来@Scheduled(fixedDelay = 5000)定期执行方法。记住@EnableScheduling为包含您的main方法的类设置。

@Scheduled注释有两个选项- fixedDelayfixedRate

fixedDelay 最后一次执行完成后,系统会在X毫秒的延迟时间内连续执行您的方法。

fixedRate将在固定日期连续执行您的方法。因此,每X毫秒,无论最后一次执行是否完成,都将执行此方法。

@Async如果要一次处理一堆对象,也可以使用。再一次,您需要@EnableAsync使用main方法添加到您的类中。

//Remember to set @EnableScheduling
//in the class containing your main method
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }
}

@Component
public class ScheduledTasks {

List<YourObject> myObjects;

    //This method will run every 5 second.
    @Scheduled(fixedDelay = 5000)
    public void yourMethodName() {
        //This will process all of your objects all at once using treads
        for(YourObject yo : myObjects){
            yo.process();
        }
    }
}

public class YourObject {

    Integer someTest = 0;

    @Async
    public void process() {
       someTest++;
    }
}

奖励
您可以通过扩展AsyncConfigurerSupport和覆盖来摆脱池大小的XML配置getAsyncExecutor。有关此方法的更多信息,请参见以下链接

我建议您看一下:

https://spring.io/guides/gs/scheduling-
tasks/

https://spring.io/guides/gs/async-method/