使用Spring的线程安全,无状态设计 [英] thread safe, stateless design using Spring

查看:138
本文介绍了使用Spring的线程安全,无状态设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我假设如果实例变量由spring IOC管理,并且是单例,那么desgin可以被称为无状态和线程安全。因此,这种类型的设计可以扩展到集群服务器。我的假设是否正确,如下所述?

I have assumed that if instance variables are managed by spring IOC, and are singletons that the desgin can be called stateless and threadsafe.This type of desgin could consequently be scaled to clustered servers. Am I correct in my assumptions,outlined below ?

@Repository("myDao")
public class MyDao implements Dao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Value("${sqlFoo}")
    private String foo;

    @Override
    public Integer getMyInt(String str) {
      return jdbcTemplate.queryForInt(foo, str);
    }

然后注入:

@Service("myService")
public class MyServiceImpl {

    @Resource(name = "myDao")
    Dao dao;

    @Override
    @Transactional(readOnly = true)
    public int getScore(String str) {
      return dao.getMyInt(str);
    }
}


推荐答案

春天bean不是无状态的,因为它们具有状态(字段)。从技术上讲,它们甚至都不可变,因为你可以随时更改注入的字段。

Spring beans aren't stateless because they have state (fields). Technically they aren't even immutable because you can change injected fields at any time.

但是你可以通过使用 final来轻松地使Spring bean不可变/ code>字段和构造函数注入。从可扩展性的观点来看,这种状态也没有问题。如果您的bean包含随时间变化的可变值,则这是群集时的主要问题。但是在Spring中,服务通常只包含在引导时注入的依赖项。因此它们实际上是无状态且不可变的。

However you can easily make Spring beans immutable by using final fields and constructor injection. Also this kind of state is not problematic from scalability point of view. If your beans contain mutable values that change over time, this is a major issue when clustering. But in Spring services typically contain only dependencies injected at bootstrap time. So they are effectively stateless and immutable.

运行相同Spring应用程序的服务器数量无关紧要 - bean和依赖项本身是安全的。 但是如果你的Spring bean包含计数器,缓存,可变地图等等 - 你需要考虑它们。

It doesn't matter on how many servers you run the same Spring application - the beans and dependencies themselves are safe. But if you Spring beans contain counters, caches, mutable maps, etc. - you need to think about them.

这篇关于使用Spring的线程安全,无状态设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆