我正在使用基于线程的方法来轮询AWS上特定任务的状态。为此,我使用while循环不断检查状态,如下面的代码所示。问题是,当代码从一项服务切换到另一项服务时,它会遇到错误-
Could not obtain transaction-synchronised hibernate session
线程中的函数如下:
Runnable task = new Runnable() {
@Override
public void run() {
Session session = null;
try {
session = sessionFactory.openSession();
RmlWorkspace rmlWorkspace = session.get(RmlWorkspace.class, id);
logger.info("Starting Status check for "+id);
if (rmlWorkspace.getCloudStack().getStatus() == RUNNING_STATUS.STARTING) {
while (rmlWorkspace.getCloudStack().getStatus() != RUNNING_STATUS.ON) {
logger.info("Checking Status for "+id);
rmlWorkspace = checkStatus(session, rmlWorkspace);
TimeUnit.SECONDS.sleep(5);
}
} else if (rmlWorkspace.getCloudStack().getStatus() == RUNNING_STATUS.STOPPING) {
while (rmlWorkspace.getCloudStack().getStatus() != RUNNING_STATUS.OFF) {
Transaction tx = session.beginTransaction();
rmlWorkspace = checkStatus(session, rmlWorkspace);
tx.commit();
TimeUnit.SECONDS.sleep(5);
}
}
session.close();
} catch (Exception e) {
logger.info(e.getMessage());
if (session != null)
session.close();
}
}
};
checkStatus
函数尝试在另一个类中使用注释@Service
调用函数。该代码在以下代码中遇到错误:
private AssumeRoleResult assumeRole() {
try {
BasicAWSCredentials credentials = new BasicAWSCredentials(configAttributeService.getAttribute("aws.iamkey"),
configAttributeService.getAttribute("aws.iampass"));
AWSSecurityTokenService client = AWSSecurityTokenServiceClientBuilder.standard()
.withRegion(Regions.US_WEST_2).withCredentials(new AWSStaticCredentialsProvider(credentials))
.build();
AssumeRoleRequest request = new AssumeRoleRequest()
.withRoleArn(configAttributeService.getAttribute("aws.assumerole"))
.withRoleSessionName(UUID.randomUUID().toString()).withDurationSeconds(900);
AssumeRoleResult assumeRoleResult = client.assumeRole(request);
return assumeRoleResult;
} catch (Exception e) {
throw e;
}
}
包含上述函数的类具有注释@Service("xxx")
有人可以解释一下原因以及如何使其正常工作。