提高
EJB性能的十大技巧
項目進行到這里,開始出現(xiàn)新的問題。EJB調(diào)用是耗時、費力的。怎么提高EJB的性能?我們?yōu)榻鉀Q這一問題,開始邊寫邊討論。等到完成了,我才發(fā)現(xiàn),我們所應用的技巧總結一下,竟有十條。把提高EJB性能的這些技巧總結一下,為以后的項目做參考。
1.用一個Session Bean封裝多個Entity Bean,將原來的多個Entity Bean的Remote調(diào)用和Local調(diào)用封裝在一個Session Bean中。所以建立一個ServerFacade,它為多個對象提供統(tǒng)一獲取EJB Home和獲取對象的接口。ServerFacade為程序要用到的所有EJB的home handle提供緩存,提高訪問JNDI Name的時間,達到提高訪問效率的目的。以后查找JNDI Name的方法都應寫在接口里,調(diào)用時直接從接口調(diào)用。
2.在EJB的Remote接口中使用粗粒度的方法,不推薦使用細粒度方法。
3.如果EJB的Remote接口獲取成功,應不再使用Remote接口,而是將Remote接口構造成一個一般的
Java對象,通過調(diào)用一般的JAVA對象的方法來達到減少對網(wǎng)絡的訪問。
4.如果你部署EJB客戶端和EJB在相同的JVM上,建設使用EJB2.0規(guī)范的Local接口代替Remote接口。
5.用"transient"關鍵字聲明不必要的數(shù)據(jù)變量,替代以前的"public"、"private"等,避免不必要的數(shù)據(jù)變量占用網(wǎng)絡資源。示例:
public class DemoCMP implements EntityBean {
transient EntityContext entCtx;
transient InitialContext initCtx;
public String id;
public String description;
…
}
6.在ejb-jar.
XML部署文件中,對Session Bean中非事務的方法,將trans-attribute屬性賦為"NotSupported"或"Never"
<ejb-jar>
…
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>abookesessionBean</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
7. 設置事務的超時時間,在JBoss中,要修改${jboss.home}/server/${jboss.configuration}/conf/jboss-service.xml ,如下所示:
<server>
…
<mbean code="org.jboss.tm.TransactionManagerService"
name="jboss:service=TransactionManager">
<attribute name="TransactionTimeout">300</attribute>
</mbean>
…
</server>
8.當事務鎖定
數(shù)據(jù)庫的行記錄時,事務應跨越可能的最小的時間。
9.調(diào)整EJB
服務器的各種參數(shù),如
線程數(shù)、EJB池大小、連接池參數(shù)等。以在JBoss修改連接池參數(shù)為示例,進行說明。如果JBoss和
MySQL相連,配置${jboss.home}/server/${jboss.configuration}/deploy/mysql-service.xml,來修改連接池參數(shù),包括MinSize、MaxSize、BlockingTimeoutMillis、IdleTimeoutMinutes、Criteria等,各參數(shù)的含義如下所示:
i.MinSize :連接池保持的最小連接數(shù)。
ii. MaxSize :連接池保持的最大連接數(shù)。
iii. BlockingTimeoutMillis :拋出異常前最大的等待連接時間。
iv. IdleTimeoutMinutes :關閉連接前連接空閑的最大時間。
v. Criteria :有ByContainerAndApplication、ByContainer、ByApplication和ByNothing等值。
下面是一個例子:
<depends optional-attribute-name="ManagedConnectionPool">
<!--embedded mbean-->
<mbean code="org.jboss.resource.connectionmanager.JBossManagedConnectionPool"
name="jboss.jca:service=LocalTxPool,name=MySqlDS">
<attribute name="MinSize">0</attribute>
<attribute name="MaxSize">50</attribute>
<attribute name="BlockingTimeoutMillis">5000</attribute>
<attribute name="IdleTimeoutMinutes">15</attribute>
<attribute name="Criteria">ByContainer</attribute>
</mbean>
</depends>
10.對于數(shù)據(jù)庫事務,應選擇較低成本的事務等級,避免造成壞數(shù)據(jù)。遞增成本的事務等級包括:
TRANSACTION_READ_UNCOMMITED,
TRANSACTION_READ_COMMITED,
TRANSACTION_REPEATABLE_READ,
TRANSACTION_SERIALIZABLE