gpt4 book ai didi

multithreading - Java : Running transaction in multithreaded environment

转载 作者:行者123 更新时间:2023-12-03 13:20:03 29 4
gpt4 key购买 nike

我们正在启动一个网站,该网站在短时间内的交易量非常大。它基本上是在给票。该代码是用Java,Spring和Hibernate编写的。我想通过产生多个线程并尝试使用JUnit测试用例来获取票证来模仿高容量。问题在于,在我的DAO类中,代码只是在我开始交易后就消失了。我的意思是在日志文件或类似的文件中没有错误跟踪。让我对我的代码的方式给出一些想法。

DAO代码:

@Repository("customerTicketDAO")
public class CustomerTicketDAO extends BaseDAOImpl {// BaseDAOImpl extends HibernateDaoSupport

public void saveCustomerTicketUsingJDBC(String customerId) {
try{
getSession().getTransaction().begin(); //NOTHING HAPPENS AFTER THIS LINE OF CODE
// A select query
Query query1 = getSession().createSQLQuery("my query omitted on purpose");
.
.
// An update query
Query query2 = getSession().createSQLQuery("my query omitted on purpose");
getSession().getTransaction().commite();
} catch (Exception e) {
}
}

可运行的代码:
public class InsertCustomerTicketRunnable implements Runnable {

@Autowired
private CustomerTicketDAO customerTicketDAO;

public InsertCustomerTicketRunnable(String customerId) {
this.customerId = customerId;
}

@Override
public void run() {
if (customerTicketDAO != null) {
customerTicketDAO.saveCustomerTicketUsingJDBC(customerId);
}
}
}

JUnit方法:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/test/resources/applicationContext-test.xml"})
public class DatabaseTest {
@Before
public void init() {
sessionFactory = (SessionFactory)applicationContext.getBean("sessionFactory");
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));

customerTicketDAO = (CustomerTicketDAO)applicationContext.getBean("customerTicketDAO");
}

@After
public void end() throws Exception {
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
SessionFactoryUtils.closeSession(session);
}

@Test
public void saveCustomerTicketInMultipleThreads () throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);

for (int i=0; i<1000; i++) {
executor.submit(new InsertCustomerTicketRunnable(i));
}

// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown();
// Wait until all threads are finish
executor.awaitTermination(1, TimeUnit.SECONDS);
}

我看不到将数据插入数据库中。有人可以指出我要去哪里吗?

谢谢
拉吉

最佳答案

SessionFactory是线程安全的,但Session不是线程安全的。所以我的猜测是,您需要在每个线程中调用SessionFactoryUtils.getSession(),以便每个线程都有自己的实例。您当前正在从主线程调用它,因此所有子线程都尝试共享同一实例。

关于multithreading - Java : Running transaction in multithreaded environment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22030912/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com