작업 관리자를 ContextService로 사용하여 인터페이스의 호출을
컨텍스트화하고 실행 특성을 지정하여 스레드 컨텍스트가 어떻게 캡처되고 실행 스레드에 적용되는지 제어할 수 있습니다.
이 태스크 정보
오브젝트 메소드가 호출될 때 스레드 컨텍스트를 표시해야 하는 애플리케이션 컴포넌트는
오브젝트에 대한 컨텍스트 프록시를 구성하기 위해
javax.enterprise.concurrent.ContextService를 구현하는,
작업 관리자를 사용할 수 있습니다. 스레드 컨텍스트는 컨텍스트 프록시를 작성할 때
작업 관리자 설정당 캡처됩니다. 인터페이스 메소드가 컨텍스트 프록시에서 호출될 때
이전에 캡처된 스레드 컨텍스트는 호출 이전에 적용되고 이후에 복원됩니다.
컨텍스트 프록시에 대한 실행 특성을 지정하여 어떻게 스레드 컨텍스트가 캡처되고 적용되는지 제어할 수 있습니다. 예를 들어,
실행 특성이 이 작동을 대체하도록 사용되지 않는 경우 컨텍스트 프록시 메소드는 중단된 실행 스레드의 스레드에 트랜잭션으로 호출됩니다.
- 스레드 컨텍스트가 필요한 메소드를 통해
인터페이스를 정의하거나 적합한 기존 인터페이스를 선택하십시오.
public interface AddressFinder {
Address getAddress(Person p) throws Exception;
}
- 인터페이스의 구현을 제공합니다.
public class DatabaseAddressFinder implements AddressFinder {
private final String resRefLookupName;
public DatabaseAddressFinder(String resRefLookupName) {
this.resRefLookupName = resRefLookupName;
}
public Address getAddress(Person p) throws Exception {
// Resource reference lookup requires the thread context of the
// application component that defines the resource reference.
DataSource ds = (DataSource) new InitialContext().lookup(
resRefLookupName);
Connection con = ds.getConnection();
try {
ResultSet r = con.createStatement().executeQuery(
"SELECT STREETADDR, CITY, STATE, ZIP " +
"FROM ADDRESSES WHERE PERSONID=" + p.id);
if (r.next())
return new Address(r.getString(1), r.getString(2),
r.getString(3), r.getInt(4));
else
return null;
} finally {
con.close();
}
}
}
- 실행 특성의 세트를 적용하는 중에 컨텍스트 서비스를 사용하여 현재 스레드에서 컨텍스트를 캡처하고 해당
컨텍스트를 통해 인스턴스를 랩핑합니다.
ContextService contextService = (ContextService) new InitialContext().lookup(
"java:comp/DefaultContextService");
Map<String, String> executionProperties =Collections.singletonMap(
ManagedTask.TRANSACTION,
ManagedTask.USE_TRANSACTION_OF_EXECUTION_THREAD)
AddressFinder addressFinder = contextService.createContextualProxy(
new DatabaseAddressFinder("java:comp/env/jdbc/MyDataSourceRef"),
executionProperties,
AddressFinder.class);
- 다른 스레드에서 컨텍스트 프록시를 사용하여 원래 스레드의 컨텍스트 아래에서 메소드를
호출하십시오.
transaction.begin();
try {
Address myAddress = addressFinder.getAddress(me); updateShippingInfo(myAddress);
} finally {
transaction.commit();
}