如何在Spring Boot中安装线程安全控制器 [英] How to have thread safe controller in spring boot

查看:89
本文介绍了如何在Spring Boot中安装线程安全控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何创建一个线程安全的控制器?

How should I create a controller which is thread safe?

按照最佳实践,控制器是单例的.

As per the best practice controllers are singleton.

考虑以下代码,其中im通过自动连接的服务Object存储用户数据,这使我的代码保持状态. 我如何使以下代码线程安全.

Consider the below code in which im storing user data through a autowired service Object ,which makes my code stateful. How would i make the below code thread safe.

@RestController
class ApiController {

    @Autowired
    IDbService< User > iDBService;

    @RequestMapping(value = "/api/adduser", method = RequestMethod.POST)
    public ResponseEntity<User> createUser(@RequestBody User user){

        User savedUser=iDBService.create(user);

        return new ResponseEntity<User>(savedUser, HttpStatus.CREATED);
    }

这是我的服务实现. 我在服务中共享了变量

Here is my Service implementation. I have shared variable in my service

public class IDbServiceImpl<T> implements IDBService<T>{

@Autowired
GenericRepository<T, Serializable> genericRepository;

@Override
public T create(T object) {
    return  genericRepository.save(object);
}

}

推荐答案

默认情况下,您的控制器是单例,默认情况下您的服务也是单例.

Your controller is a singleton by default and your service is singleton by default too.

因此,为了使它们成为线程安全的,必须确保在服务内部进行的操作必须是线程安全的,以防万一更改服务内部对象的状态.列表.

Therefore in order to make them thread safe you have to make sure that the operations that take place inside the service must be thread safe, in case of changing the state of an object inside the service ie. a list.

如果使用rdbms,则您会遇到与交易相关的问题.

In case of using a rdbms then you have a transaction related problem.

如果您使用spring和Jpa,则在使用@Transactional的情况下,事务管理器将照顾您的更新.如果使用普通的jdbc方法,则可以使用纯jdbc自己进行事务处理,也可以使用

If you use spring and Jpa, the transaction manager will take care for your updates provided that you use @Transactional. In case of plain jdbc method then you can either use pure jdbc and do the transaction handling on your own or use spring-jdbc that comes with a transaction manager.

如果您希望在写操作过程中不更改数据库行,则必须考虑与行锁定相关的机制. – gkatzioura 2月7日15:23

If you want the database rows not to be changed in case of a write in progress then you have to take into consideration row-locking related mechanisms. – gkatzioura Feb 7 at 15:23

在使用@Transactional的JPA的情况下,将完成工作.但是,根据您的应用程序,您可能必须考虑锁定.查看有关使用jpa锁定的文章.

In case of JPA using @Transactional will do the work. However depending on your application you might have to consider locking. Check this article on locking with jpa.

这篇关于如何在Spring Boot中安装线程安全控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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