锘??xml version="1.0" encoding="utf-8" standalone="yes"?>国产AV无码专区亚洲AWWW,亚洲色成人网一二三区,亚洲伊人久久综合影院http://www.tkk7.com/niumd/category/32382.html澶╄鍋ャ佸悰瀛愪互鑷己涓嶆伅 錛涘湴鍔垮潳銆佸悰瀛愪互鍘氬痙杞界墿鈥︹?/description>zh-cnWed, 11 May 2011 02:52:47 GMTWed, 11 May 2011 02:52:47 GMT60Spring JDBC Framework璇﹁В鈥斺旀壒閲廕DBC鎿嶄綔銆丱RM鏄犲皠http://www.tkk7.com/niumd/archive/2011/05/10/349965.html絀虹櫧絀虹櫧Tue, 10 May 2011 13:06:00 GMThttp://www.tkk7.com/niumd/archive/2011/05/10/349965.htmlhttp://www.tkk7.com/niumd/comments/349965.htmlhttp://www.tkk7.com/niumd/archive/2011/05/10/349965.html#Feedback0http://www.tkk7.com/niumd/comments/commentRss/349965.htmlhttp://www.tkk7.com/niumd/services/trackbacks/349965.html

浣滆咃細niumd錛岃漿杞借娉ㄦ槑鍑哄錛岃阿璋?nbsp;  

鍙戣〃鏃墮棿錛?010 騫?nbsp;03 鏈?nbsp;17 鏃?nbsp; 

鍘熸枃閾炬帴錛?a mce_href="/admin/blogs/618449">http://ari.iteye.com/admin/blogs/618449


涓銆丼pring JDBC 姒傝堪

     Spring 鎻愪緵浜嗕竴涓己鏈夊姏鐨勬ā鏉跨被JdbcTemplate綆鍖朖DBC鎿嶄綔錛孌ataSource,JdbcTemplate閮藉彲浠ヤ互Bean鐨勬柟寮忓畾涔夊湪鎯硏ml閰嶇疆鏂囦歡錛孞dbcTemplate鍒涘緩鍙渶娉ㄥ叆涓涓狣ataSource錛屽簲鐢ㄧ▼搴廌ao灞傚彧闇瑕佺戶鎵縅dbcDaoSupport, 鎴栬呮敞鍏dbcTemplate錛屼究鍙互鑾峰彇JdbcTemplate錛孞dbcTemplate鏄竴涓嚎紼嬪畨鍏ㄧ殑綾伙紝澶氫釜Dao鍙互娉ㄥ叆涓涓狫dbcTemplate錛?/p>



<!--         Oracle鏁版嵁婧?          -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@oracle.devcake.co.uk:1521:INTL"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--  set娉ㄥ叆鏂瑰紡鑾峰彇jdbcTemplate -->
<bean id="customerDao" class="JdbcCustomerDao" >
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<!-- 娉ㄥ叆dataSource錛宑ustomerDao閫氳繃緇ф壙JdbcDaoSupport ,浣跨敤this.getJdbcTemplate()鑾峰彇JdbcTemplate   -->
<bean id="customerDao" class="JdbcCustomerDao" >
<property name="dataSource" ref="dataSource"/>
</bean>


鐒跺悗灝唈dbcTemplate瀵硅薄娉ㄥ叆鑷畾涔夌殑Dao銆佹垨鑰呯戶鎵縅dbcDaoSupport錛屼緥濡傦細

public class JdbcCustomerDao extends JdbcDaoSupport implements CustomerDao {
}
public class JdbcCustomerDao implements CustomerDao {
private JdbcTemplate jdbcTemplate
public void setJdbcTemplate()JdbcTemplate jdbcTemplate{
this.jdbcTemplate=jdbcTemplate
}
}


浜屻?nbsp;JdbcTemplate 鎻愪緵浠ヤ笅涓昏鏂規硶綆鍖朖DBC鎿嶄綔錛?/strong>

2.1銆丩ist query(String sql,Ojbect[] args,RowMapper rowMapper)

     璇存槑錛氬父鐢ㄧ殑鏌ヨ錛宻ql寰呮墽琛岀殑sql璇彞錛宎rgs鏄痵ql璇彞鐨勫弬鏁幫紝rowMapper璐熻矗灝嗘瘡涓琛岃褰曡漿鍖栦負java瀵硅薄瀛樻斁鍦╨ist錛屽茍鏈緇堣繑鍥烇紝渚嬪錛?/p>

public List<Book> queryByAuthor(String author) {
String sql = "select * from book where author=?";
Collection c = getJdoTemplate().find(sql,
new Object[] { author },new BookRowMapper());
List<Book> books = new ArrayList<Book>();
books.addAll(c);
return books;
}
class BookRowMapper implements RowMapper{
public Object mapRow(ResultSet res, int index) throws SQLException {
Book book = new Book();
book.setId(rs.getInt("id"));
//鐪佺暐set
return book錛?
}
}


   鏇存柊銆佸垹闄ゃ佸叾浠栨煡璇㈡搷浣滅被浼鹼紝涓句緥濡備笅錛岃緇嗙粏鑺傝鍙傝僺pring api錛?/p>


//榪斿洖鍊間負涓涓暱鏁村艦
public long getAverageAge() {
return getJdbcTemplate().queryForLong("SELECT AVG(age) FROM employee");
}
//榪斿洖涓涓暣鏁?
public int getTotalNumberOfEmployees() {
return getJdbcTemplate().queryForInt("SELECT COUNT(0) FROM employees");
}
//鏇存柊鎿嶄綔
this.jdbcTemplate.update(
"insert into t_actor (first_name, surname) values (?, ?)",
new Object[] {"Leonor", "Watling"});



 2.2銆乻pring 2.5鏂板姛鑳斤紝鍙︾被鐨刯dbc ORM錛欱eanPropertyRowMapper


      涓婇潰鎴戜滑媯绱㈡椂蹇呴』瀹炵幇RowMapper錛屽皢緇撴灉闆嗚漿鍖栦負java瀵硅薄銆係pring2.5 綆鍖栦簡榪欎竴鎿嶄綔錛屼嬌寰楁垜浠笉蹇呭啀瀹炵幇RowMapper錛屽疄鐜版鍔熻兘鐨勪咯涓濂囦笢涓滀究鏄細ParameterizedRowMapper錛孭arameterizedBeanPropertyRowMapper錛岃矊浼奸氳繃java鍙嶅皠鏈哄埗瀹炵幇浜嗗皢resultset瀛楁鏄犲皠鍒癹ava瀵硅薄錛屼絾鏄暟鎹〃鐨勫垪蹇呴』鍜宩ava瀵硅薄鐨勫睘鎬у搴旓紝娌℃湁鐮旂┒婧愮爜錛屾湁鐐圭被浼間簬apache 鐨凚eanUtil錛屼笉鐭ヤ負浣曡繖閮ㄥ垎鍦╯pring寮鍙戝弬鑰冩墜鍐屾病鏈夛紝闅鵑亾涓嶆槸緇忓吀銆?/p>



//浣跨敤ParameterizedBeanPropertyRowMapper
@SuppressWarnings({"unchecked"})
public List<Customer> getAll() {
return getJdbcTemplate().query("select * from t_customer", ParameterizedBeanPropertyRowMapper.newInstance(Customer.class));
}
//浣跨敤BeanPropertyRowMapper
@SuppressWarnings({"unchecked"})
public List<Customer> getAll() {
return getJdbcTemplate().query("select * from t_customer", new BeanPropertyRowMapper(Customer.class));
}



娉ㄦ剰錛歅arameterizedBeanPropertyRowMapper鏄疊eanPropertyRowMapper瀛愮被銆傚彟澶栬〃鐨勫瓧孌靛悕縐板繀欏誨拰瀹炰綋綾葷殑鎴愬憳鍙橀噺鍚嶇О涓鑷達紱


2.3銆乻pring涔婮DBC鎵歸噺鎿嶄綔

      jdbcTemplate.batchUpdate(final String[] sql) 錛孉PI瑙i噴錛欼ssue multiple SQL updates on a single JDBC Statement using batching錛岀炕璇戣繃鏉ュぇ鑷翠負錛氳В鍐沖涓猻ql鐨勬彃鍏ャ佹洿鏂般佸垹闄ゆ搷浣滃湪涓涓猄tatement涓傛ц兘涓鑸?/span>

   jdbcTemplate.batchUpdate(String sql, final BatchPreparedStatementSetter pss),綾諱技浜嶫DBC鐨凱reparedStatement錛屾ц兘杈冧笂鐫鏈夋墍鎻愰珮銆?/span>

   鎴戜滑涓句緥璇存槑濡備綍浣跨敤錛岀ず渚嬪涓?

final int count = 2000;
final List<String> firstNames = new ArrayList<String>(count);
final List<String> lastNames = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
firstNames.add("First Name " + i);
lastNames.add("Last Name " + i);
}
jdbcTemplate.batchUpdate(
"insert into customer (id, first_name, last_name, last_login, comments) values (?, ?, ?, ?, ?)",
new BatchPreparedStatementSetter() {
//涓簆repared statement璁劇疆鍙傛暟銆傝繖涓柟娉曞皢鍦ㄦ暣涓繃紼嬩腑琚皟鐢ㄧ殑嬈℃暟
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setLong(1, i + 10);
ps.setString(2, firstNames.get(i));
ps.setString(3, lastNames.get(i));
ps.setNull(4, Types.TIMESTAMP);
ps.setNull(5, Types.CLOB);
}
//榪斿洖鏇存柊鐨勭粨鏋滈泦鏉℃暟
public int getBatchSize() {
return count;
}
});
}



  BatchSqlUpdate綾繪槸SqlUpdate 鐨勫瓙綾伙紝閫傜敤浜庢彃鍏ャ佸垹闄ゃ佹洿鏂版壒閲忔搷浣滐紝鍐呴儴浣跨敤PreparedStatement錛屾墍浠ユ晥鐜囧緢楂橈紝鎵歸噺璇彞杈懼埌璁懼畾鐨刡atchSize錛屾垨鑰呮墜鍔ㄨ皟鐢╢lush鎵嶄細鎵ц鎵歸噺鎿嶄綔銆傛敞鎰忥細姝ょ被鏄潪綰跨▼瀹夊叏鐨勶紝蹇呴』涓烘瘡涓嬌鐢ㄨ呭垱寤轟竴涓疄渚嬶紝鎴栬呭湪鍚屼竴涓嚎紼嬩腑浣跨敤鍓嶈皟鐢╮eset銆?/span>

   涓嬮潰鎴戜滑涓句緥璇存槑濡備綍浣跨敤BatchSqlUpdate錛屾潵鎵ц鎵歸噺鎿嶄綔銆傜ず渚嬪涓嬶細

class BatchInsert extends BatchSqlUpdate {
private static final String SQL = "insert into t_customer (id, first_name, last_name, last_login, "
+ "comments) values (?, ?, ?, ?, null)";
BatchInsert(DataSource dataSource) {
super(dataSource, SQL);
declareParameter(new SqlParameter(Types.INTEGER));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.TIMESTAMP));
setBatchSize(10);
}
}


int count = 5000;
for (int i = 0; i < count; i++) {
batchInsert.update(new Object[] { i + 100L, "a" + i, "b" + i, null });
}


 鑷蟲錛宻pring JDBC涓昏鐨勫簲鐢ㄥ熀鏈笂閮界畝鍗曠綏鍒椾竴鐣紝鎵鏈変唬鐮佸潎涓烘枃绔犱婦渚嬶紝涓嶆槸寰堜弗璋紝浠呬負婕旂ず姣忎竴縐嶇敤娉曪紝鎶涚爾寮曠帀錛屽笇鏈涙湁鐙壒瑙佽В鐨勬媿鐮栵紝鏈夐棶棰樼殑璇鋒寚鏄庨棶棰樻墍鍦?璋㈣阿



絀虹櫧 2011-05-10 21:06 鍙戣〃璇勮
]]>
Tomcat6.x鐩綍涓巗erver.xml璇﹁Вhttp://www.tkk7.com/niumd/archive/2011/05/10/349964.html絀虹櫧絀虹櫧Tue, 10 May 2011 13:04:00 GMThttp://www.tkk7.com/niumd/archive/2011/05/10/349964.htmlhttp://www.tkk7.com/niumd/comments/349964.htmlhttp://www.tkk7.com/niumd/archive/2011/05/10/349964.html#Feedback0http://www.tkk7.com/niumd/comments/commentRss/349964.htmlhttp://www.tkk7.com/niumd/services/trackbacks/349964.html闃呰鍏ㄦ枃

絀虹櫧 2011-05-10 21:04 鍙戣〃璇勮
]]>
欏圭洰閲嶆瀯涔嬪懡浠ゆā寮?/title><link>http://www.tkk7.com/niumd/archive/2011/05/10/349962.html</link><dc:creator>絀虹櫧</dc:creator><author>絀虹櫧</author><pubDate>Tue, 10 May 2011 13:03:00 GMT</pubDate><guid>http://www.tkk7.com/niumd/archive/2011/05/10/349962.html</guid><wfw:comment>http://www.tkk7.com/niumd/comments/349962.html</wfw:comment><comments>http://www.tkk7.com/niumd/archive/2011/05/10/349962.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.tkk7.com/niumd/comments/commentRss/349962.html</wfw:commentRss><trackback:ping>http://www.tkk7.com/niumd/services/trackbacks/349962.html</trackback:ping><description><![CDATA[<div style="color: #000000; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; margin-top: 8px; margin-right: 8px; margin-bottom: 8px; margin-left: 8px; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: #ffffff; background-position: initial initial; background-repeat: initial initial; "> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; ">    欏圭洰涓湁涓笟鍔″鐞嗙被澶у皬117K錛屼唬鐮?700琛岋紝鐪嬫綾誨樊鐐歸浄姝繪垜錛屽浠婂瑕佸鍔犱笟鍔¢昏緫澶х害20涓惂錛屾綾誨鏋滈殢鐫欏圭洰宸ョ▼鐨勪簩鏈熴佷笁鏈熷嬈℃坊鍔犻昏緫榪熸棭鏈変竴澶╁ぇ灝忚揪鍒癕錛屽櫌銆乵ygod銆傜粏蹇冪爺璇誨墠浜虹殑宸ヤ綔鎬葷粨錛屽彂鐜板叾涓湁鐐瑰彲鏀歸犵殑铔涗笣椹抗(鏈漢寰堢銆佸埆絎戞垜鎵嶅彂鐜板浣曟敼閫?銆?/p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; ">     涓嬮潰鎴戜滑瀵逛笟鍔℃祦紼嬨佷互鍙婃秹鍙婄殑鐩稿叧綾昏繘琛屼粙緇嶏紝<span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">Msg</span>浠h〃鎺ュ彈鍒板鎴風鐨勪竴涓秷鎭姤鏂囷紝娑堟伅鎶ユ枃緇撴瀯錛氭秷鎭ご<span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">+</span></span>娑堟伅浣擄紝娑堟伅澶村弬鏁板浐瀹氥佹秷鎭綋鍙傛暟涓嶅畾錛屼笅闈㈡槸涓涓畝鍗曠殑綾誨浘錛岃繖鍙槸涓涓ā鎷熷満鏅紝<span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">****Req</span></span>浠h〃鍚勬埛绔姹傜被錛?span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">***Rsp</span></span>浠h〃榪斿洖緇欏鎴風鐨勫弬鏁扮被銆傚疄闄呮瘮姝ゅ鏉傦紝涓烘弿榪伴棶棰樻垜浠畝鍗曟憳闄ゅ嚑涓被浠嬬粛錛屽埆闂垜涓轟綍榪欎箞璁捐緇ф壙銆傜被鍥?span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">msg</span></span>涓?span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">msgHead</span></span>鏄粍鍚堝叧緋諱篃璁哥敾閿欎簡銆佷笉褰撲箣澶勮鎸囧嚭錛屽嬁鎭惰鍚戜激錛?/span></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><span lang="EN-US"> </span></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "> <br /> <img src="http://dl.iteye.com/upload/attachment/264052/9e823571-e81c-35d0-a4e5-b5b14b525542.png" mce_src="http://dl.iteye.com/upload/attachment/264052/9e823571-e81c-35d0-a4e5-b5b14b525542.png" alt="" style="border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; " /><br />  澶勭悊璇鋒眰Handler綾葷殑浠g爜閫昏緫濡備笅錛?/p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <pre name="code" class="java" style="color: #000000; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; margin-top: 0px; margin-right: 5px; margin-bottom: 5px; margin-left: 15px; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: #cccccc; border-right-color: #cccccc; border-bottom-color: #cccccc; border-left-color: #cccccc; padding-top: 3px; padding-right: 3px; padding-bottom: 3px; padding-left: 3px; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: #fafafa; background-position: initial initial; background-repeat: initial initial; ">//綾諱腑涓昏鏂規硶濡備笅 public void execute(Object object) { Message message = (Message)object; int opcode = message.getOpcode(); int connectId = message.getConnectId(); //娑堟伅澶村凡緇忚В鏋愶紝鑾峰彇娑堟伅浣擄紝鍗沖瓙綾誨睘鎬у瓧鑺傛暟緇? byte[] bytes = message.getBytes(); if (opcode == MsgInfo.ADD_RING) { // 璁㈣喘褰╅搩 orderRing(connectId, bytes); } else if (opcode == MsgInfo.PRESENT_RING) { // 璧犻佸僵閾? presentRing(connectId, bytes); } else if (opcode == MsgInfo.DEL_RING) { // 鍒犻櫎涓漢閾冮煶 delPersonalRing(connectId, bytes); } //姝ゅ鐪佺暐n涓猠lse if } //鍏朵粬鍒犻櫎銆佽禒閫佷笌鐪佺暐鐨別lse if涓殑澶勭悊閫昏緫涓庝箣鍩烘湰鐩稿悓 private void orderRing(int connectId, byte[] bytes) { //澶勭悊鏂規硶鍒嗕負鍥涙錛屽叿浣撲唬鐮佺渷鐣? //1銆佽В鏋愬瓧鑺傛暟緇勪負璁㈣喘閾冮煶綾? //2銆佸鐞嗚璐叧緋? //3銆佸鐞嗙粨鏋滃皝瑁呬負璁㈣喘鍝嶅簲綾? //4銆佸彂閫佸洖瀹㈡埛绔? } //鐪佺暐presentRing銆乨elPersonalRing絳変竴緋誨垪鍏朵粬鏂規硶錛屾墍鏈夌殑澶勭悊鏂規硶鍙傛暟鐩稿悓…… </pre> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; ">    閴翠簬姝ゃ佹兂鍒頒嬌鐢ㄥ懡浠ゆā寮忔敼閫犳綾伙紝濡傛灉涓嶄簡瑙e懡浠ゆā寮忚闃呰鐩稿叧涔︾睄錛屽ぇ璇濊璁℃ā寮忔垨璁捐涓庢ā寮忥紝榪欓噷鎴戜滑浠呯粰鍑哄ぇ鑷寸殑瀹氫簬涓庣被鍥俱?/p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; ">浣曡皳鍛戒護妯″紡錛氬皢涓涓姹傚皝瑁呬負涓涓璞★紝浠庤屾槸浣犲彲鐢ㄤ笉鍚岀殑璇鋒眰瀵瑰鎴風鍙傛暟鍖栵紝瀵硅姹傛帓闃熸垨璁板綍鏃ュ織錛屼互鍙婃敮鎸佸彲鎾ら攢鐨勬搷浣溿?/p> <p class="MsoNormal" mce_style="text-indent: 15.75pt; margin: 0cm 0cm 0pt;" style="margin-top: 0cm; margin-right: 0cm; margin-bottom: 0pt; margin-left: 0cm; text-indent: 15.75pt; "> <span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">Shit</span></span>銆佽繖鍙ヨ瘽寰堥毦鐞嗚В鍝︼紝閭e氨鍏堝埆鐞嗚В浜嗭紝鎴戜滑鐪嬩笅鍛戒護妯″紡鐨勭被鍥撅紝鐒跺悗浠嬬粛濡備綍浣跨敤鍛戒護妯″紡鏀歸犱笂闈㈢殑<span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">elseif</span></span>銆?/p> <p class="MsoNormal" mce_style="text-indent: 21pt; margin: 0cm 0cm 0pt;" style="margin-top: 0cm; margin-right: 0cm; margin-bottom: 0pt; margin-left: 0cm; text-indent: 21pt; ">綾誨浘鍏堢渷鐣ワ紝涓婄彮鍋風┖鍐欑殑錛?/p> <p class="MsoNormal" mce_style="text-indent: 21pt; margin: 0cm 0cm 0pt;" style="margin-top: 0cm; margin-right: 0cm; margin-bottom: 0pt; margin-left: 0cm; text-indent: 21pt; "><span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; "> </span></span></p> <p class="MsoNormal" mce_style="text-indent: 21pt; margin: 0cm 0cm 0pt;" style="margin-top: 0cm; margin-right: 0cm; margin-bottom: 0pt; margin-left: 0cm; text-indent: 21pt; ">涓嬮潰榪涘叆姝i錛屽<span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">Handler</span></span>灝忔墜鏈紑濮嬶紝涓昏鑰冭檻濡備笅錛?/p> <p class="MsoListParagraph" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><strong><span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">1銆?/span></span>鎻愮偧鏂規硶</strong></p> <p class="MsoListParagraph" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; ">     灝嗘瘡涓?span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">if</span></span>璇彞鍧椾腑鐨勯昏緫鎻愬彇涓轟竴涓柟娉曪紝榪欓噷鎴戜滑鐨?span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">handler</span></span>宸茬粡瀹炵幇錛屽氨鏄細<span mce_style="font-family: 'Courier New'; color: black; font-size: 10pt;" style="font-family: 'Courier New'; color: black; font-size: 10pt; ">orderRing</span>銆?span mce_style="font-family: 'Courier New'; color: black; font-size: 10pt;" style="font-family: 'Courier New'; color: black; font-size: 10pt; ">presentRing</span>銆?span mce_style="font-family: 'Courier New'; color: black; font-size: 10pt;" style="font-family: 'Courier New'; color: black; font-size: 10pt; ">delPersonalRing</span>銆?#8230;…銆?/p> <p class="MsoListParagraph" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><strong><span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">2銆?/span></span>鎻愮偧綾?/strong></p> <p class="MsoListParagraph" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; ">  灝嗘瘡涓笟鍔″鐞嗘柟娉曟彁鍙栦負浠ュ悇綾伙紝鐒跺悗瀵瑰叿浣撶被榪涜鎶借薄錛屾彁鍙栫埗綾繪垨鑰呮帴鍙o紱浠g爜濡備笅錛?/p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <pre name="code" class="java" style="color: #000000; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; margin-top: 0px; margin-right: 5px; margin-bottom: 5px; margin-left: 15px; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: #cccccc; border-right-color: #cccccc; border-bottom-color: #cccccc; border-left-color: #cccccc; padding-top: 3px; padding-right: 3px; padding-bottom: 3px; padding-left: 3px; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: #fafafa; background-position: initial initial; background-repeat: initial initial; ">public Abstract class Command{ public void execute() 锝? public class OrderRingCommand extends Command { private Handler hander; public OrderRingCommand(Handler hander){ this.hander = hander; } public void execute(int connectId, byte[] bytes){ //1銆佽В鏋愬瓧鑺傛暟緇勪負璁㈣喘閾冮煶綾? //2銆佸鍔犺璐叧緋? //3銆佸鐞嗙粨鏋滃皝瑁呬負璁㈣喘鍝嶅簲綾? //4銆佸彂閫佸洖瀹㈡埛绔? } /** * 1銆佽В鏋愬瓧鑺傛暟緇勪負璁㈣喘閾冮煶綾? */ public void method1(){ } /** * 2銆佸鐞嗚璐叧緋? */ public void method2(){ } /** * 3銆佸鐞嗙粨鏋滃皝瑁呬負璁㈣喘鍝嶅簲綾? */ public void method3(){ } /** * 4銆佺粨鏋滃彂閫佸洖瀹㈡埛绔? */ public void method4(){ } } public class DelRingCommand extends Command { private Handler hander; public DelRingCommand(Handler hander){ this.hander = hander; } public void execute(int connectId, byte[] bytes){ //1銆佽В鏋愬瓧鑺傛暟緇勪負璁㈣喘閾冮煶綾? //2銆佸垹闄よ喘鍏崇郴 //3銆佸鐞嗙粨鏋滃皝瑁呬負璁㈣喘鍝嶅簲綾? //4銆佸彂閫佸洖瀹㈡埛绔? } //鎻愬彇鏂規硶 } </pre> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "> <span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "> </span></span></span></span></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><strong><span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; ">3銆?/span></span>鍛戒護妯″紡鏀歸犳浛鎹?/strong><span lang="EN-US"><span mce_style="font-family: Calibri;" style="font-family: Calibri; "><strong>elseif錛?/strong></span></span></p> <p class="MsoListParagraph" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <pre name="code" class="java" style="color: #000000; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; margin-top: 0px; margin-right: 5px; margin-bottom: 5px; margin-left: 15px; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: #cccccc; border-right-color: #cccccc; border-bottom-color: #cccccc; border-left-color: #cccccc; padding-top: 3px; padding-right: 3px; padding-bottom: 3px; padding-left: 3px; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: #fafafa; background-position: initial initial; background-repeat: initial initial; ">Map<Integer, Command> map = new HashMap<Integer,Command>(); static{ map.put(MsgInfo.ADD_RING, new OrderRingCommand()); //鐪佸嵈鍏朵粬錛岃繖閲屼粎涓烘紨紺猴紝瀹為檯欏圭洰涓疄渚嬪寲綾婚氳繃spring瀹瑰櫒鎴栬呭叾浠栨柟娉? } public void execute(Object object) { Message message = (Message)object; int opcode = message.getOpcode(); int connectId = message.getConnectId(); //娑堟伅澶村凡緇忚В鏋愶紝鑾峰彇娑堟伅浣擄紝鍗沖瓙綾誨睘鎬у瓧鑺傛暟緇? byte[] bytes = message.getBytes(); map.get(opcode).execute(connectId,bytes); } </pre> <p class="MsoListParagraph" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "></span></span></span></span></span></span></span></span></span></span></span></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; ">     <span lang="EN-US"></span></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "></span></span></span></span></span></span></span></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><span lang="EN-US"></span></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><span lang="EN-US"> 鍛戒護妯″紡鏇挎崲else if浠g爜鍧忓懗閬撶殑閲嶆瀯緇撴潫錛屼紬澶氱殑if鏉′歡鍧楃儫娑堜簯鏁o紝鍙栬屼唬涔嬬殑鏄竴涓釜綺劇畝鐨勭被錛宒oc鐗堟湰鍦ㄩ檮浠朵腑</span></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><span lang="EN-US"><font><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><font mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "></font></span></span></span></span></span></span></font></span></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><font><font mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><br /> </font></font></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p class="MsoListParagraph" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p class="MsoListParagraph" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "><span mce_style="font-size: 10.5pt;" style="font-size: 10.5pt; "></span></span></span></span></span></span></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p class="MsoListParagraph" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "></p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p class="MsoListParagraph" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> <p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; "><br /> </p> </div> <img src ="http://www.tkk7.com/niumd/aggbug/349962.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.tkk7.com/niumd/" target="_blank">絀虹櫧</a> 2011-05-10 21:03 <a href="http://www.tkk7.com/niumd/archive/2011/05/10/349962.html#Feedback" target="_blank" style="text-decoration:none;">鍙戣〃璇勮</a></div>]]></description></item><item><title>娣卞叆嫻呭嚭ThreadLocalhttp://www.tkk7.com/niumd/archive/2011/05/10/349961.html絀虹櫧絀虹櫧Tue, 10 May 2011 13:02:00 GMThttp://www.tkk7.com/niumd/archive/2011/05/10/349961.htmlhttp://www.tkk7.com/niumd/comments/349961.htmlhttp://www.tkk7.com/niumd/archive/2011/05/10/349961.html#Feedback0http://www.tkk7.com/niumd/comments/commentRss/349961.htmlhttp://www.tkk7.com/niumd/services/trackbacks/349961.html

涓銆乀hreadLocal姒傝堪

       瀛︿範JDK涓殑綾伙紝棣栧厛鐪嬩笅JDK API瀵規綾葷殑鎻忚堪錛屾弿榪板涓嬶細

JDK API 鍐欓亾
璇ョ被鎻愪緵浜嗙嚎紼嬪眬閮?(thread-local) 鍙橀噺銆傝繖浜涘彉閲忎笉鍚屼簬瀹冧滑鐨勬櫘閫氬搴旂墿錛屽洜涓鴻闂煇涓彉閲忥紙閫氳繃鍏?get 鎴?set 鏂規硶錛夌殑姣忎釜綰跨▼閮芥湁鑷繁鐨勫眬閮ㄥ彉閲忥紝瀹冪嫭绔嬩簬鍙橀噺鐨勫垵濮嬪寲鍓湰銆俆hreadLocal 瀹炰緥閫氬父鏄被涓殑 private static 瀛楁錛屽畠浠笇鏈涘皢鐘舵佷笌鏌愪竴涓嚎紼嬶紙渚嬪錛岀敤鎴?ID 鎴栦簨鍔?ID錛夌浉鍏寵仈銆?nbsp;

    API琛ㄨ揪浜嗕笅闈㈠嚑縐嶈鐐癸細

1銆乀hreadLocal涓嶆槸綰跨▼錛屾槸綰跨▼鐨勪竴涓彉閲忥紝浣犲彲浠ュ厛綆鍗曠悊瑙d負綰跨▼綾葷殑灞炴у彉閲忋?/p>

2銆乀hreadLocal 鍦ㄧ被涓氬父瀹氫箟涓洪潤鎬佺被鍙橀噺銆?/p>

3銆佹瘡涓嚎紼嬫湁鑷繁鐨勪竴涓猅hreadLocal錛屽畠鏄彉閲忕殑涓涓?#8216;鎷瘋礉’錛屼慨鏀瑰畠涓嶅獎鍝嶅叾浠栫嚎紼嬨?/p>


    鏃㈢劧瀹氫箟涓虹被鍙橀噺錛屼負浣曚負姣忎釜綰跨▼緇存姢涓涓壇鏈紙濮戜笖鎴愪負‘鎷瘋礉’瀹規槗鐞嗚В錛夛紝璁╂瘡涓嚎紼嬬嫭绔嬭闂紵澶氱嚎紼嬬紪紼嬬殑緇忛獙鍛婅瘔鎴戜滑錛屽浜庣嚎紼嬪叡浜祫婧愶紙浣犲彲浠ョ悊瑙d負灞炴э級錛岃祫婧愭槸鍚﹁鎵鏈夌嚎紼嬪叡浜紝涔熷氨鏄榪欎釜璧勬簮琚竴涓嚎紼嬩慨鏀規槸鍚﹀獎鍝嶅彟涓涓嚎紼嬬殑榪愯錛屽鏋滃獎鍝嶆垜浠渶瑕佷嬌鐢╯ynchronized鍚屾錛岃綰跨▼欏哄簭璁塊棶銆?/p>


   ThreadLocal閫傜敤浜庤祫婧愬叡浜絾涓嶉渶瑕佺淮鎶ょ姸鎬佺殑鎯呭喌錛屼篃灝辨槸涓涓嚎紼嬪璧勬簮鐨勪慨鏀癸紝涓嶅獎鍝嶅彟涓涓嚎紼嬬殑榪愯錛涜繖縐嶈璁℃槸‘絀洪棿鎹㈡椂闂?#8217;錛宻ynchronized欏哄簭鎵ц鏄?strong>‘鏃墮棿鎹㈠彇絀洪棿’銆?/p>


浜屻乀hreadLocal鏂規硶浠嬬粛



 T get() 
          榪斿洖姝ょ嚎紼嬪眬閮ㄥ彉閲忕殑褰撳墠綰跨▼鍓湰涓殑鍊箋?/td>
protected  T initialValue() 
          榪斿洖姝ょ嚎紼嬪眬閮ㄥ彉閲忕殑褰撳墠綰跨▼鐨?#8220;鍒濆鍊?#8221;銆?/td>
 void remove() 
          縐婚櫎姝ょ嚎紼嬪眬閮ㄥ彉閲忓綋鍓嶇嚎紼嬬殑鍊箋?/td>
 void set(T value) 
          灝嗘綰跨▼灞閮ㄥ彉閲忕殑褰撳墠綰跨▼鍓湰涓殑鍊艱緗負鎸囧畾鍊箋?/td>


涓夈佹繁鍏ユ簮鐮?/strong>

    ThreadLocal鏈変竴涓猅hreadLocalMap闈欐佸唴閮ㄧ被錛屼綘鍙互綆鍗曠悊瑙d負涓涓狹AP錛岃繖涓?#8216;Map’涓烘瘡涓嚎紼嬪鍒朵竴涓彉閲忕殑‘鎷瘋礉’瀛樺偍鍏朵腑銆?/p>

    褰撶嚎紼嬭皟鐢═hreadLocal.get()鏂規硶鑾峰彇鍙橀噺鏃?棣栧厛鑾峰彇褰撳墠綰跨▼寮曠敤錛屼互姝や負key鍘昏幏鍙栧搷搴旂殑ThreadLocalMap錛屽鏋滄‘Map’涓嶅瓨鍦ㄥ垯鍒濆鍖栦竴涓紝鍚﹀垯榪斿洖鍏朵腑鐨勫彉閲忥紝浠g爜濡備笅錛?/p>


 public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}

    璋冪敤get鏂規硶濡傛灉姝ap涓嶅瓨鍦ㄩ鍏堝垵濮嬪寲錛屽垱寤烘map錛屽皢綰跨▼涓簁ey錛屽垵濮嬪寲鐨剉laue瀛樺叆鍏朵腑錛屾敞鎰忔澶勭殑initialValue錛屾垜浠彲浠ヨ鐩栨鏂規硶錛屽湪棣栨璋冪敤鏃跺垵濮嬪寲涓涓傚綋鐨勫箋俿etInitialValue浠g爜濡備笅錛?/p>

    private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}


    set鏂規硶鐩稿姣旇緝綆鍗曞鏋滅悊瑙d互涓婁咯涓柟娉曪紝鑾峰彇褰撳墠綰跨▼鐨勫紩鐢紝浠巑ap涓幏鍙栬綰跨▼瀵瑰簲鐨刴ap錛屽鏋渕ap瀛樺湪鏇存柊緙撳瓨鍊鹼紝鍚﹀垯鍒涘緩騫跺瓨鍌紝浠g爜濡備笅錛?/p>

    public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}


    瀵逛簬ThreadLocal鍦ㄤ綍澶勫瓨鍌ㄥ彉閲忓壇鏈紝鎴戜滑鐪媑etMap鏂規硶錛氳幏鍙栫殑鏄綋鍓嶇嚎紼嬬殑ThreadLocal綾誨瀷鐨則hreadLocals灞炴с傛樉鐒跺彉閲忓壇鏈瓨鍌ㄥ湪姣忎竴涓嚎紼嬩腑銆?/p>


/**
* 鑾峰彇綰跨▼鐨凾hreadLocalMap 灞炴у疄渚?
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}


    涓婇潰鎴戜滑鐭ラ亾鍙橀噺鍓湰瀛樻斁浜庝綍澶勶紝榪欓噷鎴戜滑綆鍗曡涓嬪浣曡java鐨勫瀮鍦炬敹闆嗘満鍒舵敹闆嗭紝褰撴垜浠笉鍦ㄤ嬌鐢ㄦ槸璋冪敤set(null)錛屾鏃朵笉鍦ㄥ皢寮曠敤鎸囧悜璇?#8216;map’錛岃岀嚎紼嬮鍑烘椂浼氭墽琛岃祫婧愬洖鏀舵搷浣滐紝灝嗙敵璇風殑璧勬簮榪涜鍥炴敹錛屽叾瀹炲氨鏄皢灞炴х殑寮曠敤璁劇疆涓簄ull銆傝繖鏃跺凡緇忎笉鍦ㄦ湁浠諱綍寮曠敤鎸囧悜璇ap錛屾晠鑰屼細琚瀮鍦炬敹闆嗐?/p>


 鍥涖乀hreadLocal搴旂敤紺轟緥


      鍦ㄦ垜鐨勫彟涓綃囨枃绔狅紝瀵筎hreadLocal鐨勪嬌鐢ㄥ仛浜嗕竴涓疄渚嬶紝姝ょず渚嬩篃鍙互鐢ㄤ綔鐢熶駭鐜錛岃鍙傝錛?a mce_href="/blog/757641">http://ari.iteye.com/blog/757641



濡傛湁闂璇風暀璦璁ㄨ錛岃阿璋?/p>

絀虹櫧 2011-05-10 21:02 鍙戣〃璇勮
]]>
ThreadLocal紺轟緥http://www.tkk7.com/niumd/archive/2011/05/10/349960.html絀虹櫧絀虹櫧Tue, 10 May 2011 13:01:00 GMThttp://www.tkk7.com/niumd/archive/2011/05/10/349960.htmlhttp://www.tkk7.com/niumd/comments/349960.htmlhttp://www.tkk7.com/niumd/archive/2011/05/10/349960.html#Feedback0http://www.tkk7.com/niumd/comments/commentRss/349960.htmlhttp://www.tkk7.com/niumd/services/trackbacks/349960.html

    鏈枃鍊熻姳鐚經錛屽紩鐢═im Cull鐨勫崥鏂?#8220;SimpleDateFormat: Performance Pig”浠嬬粛涓婽hreadLocal鐨勭畝鍗曚嬌鐢紝鍚屾椂涔熷SimpleDateFormat鐨勪嬌鐢ㄦ湁涓繁鍏ョ殑浜嗚В銆?/p>

Tim Cull 鍐欓亾
Just yesterday I came across this problem “in the wild” for the third time in my career so far: an application with performance problems creating tons of java.text.SimpleDateFormat instances. So, I have to get this out there: creating a new instance of SimpleDateFormat is incredibly expensive and should be minimized. In the case that prompted this post, I was using JProfiler to profile this code that parses a CSV file and discovered that 50% of the time it took to suck in the file and make 55,000 objects out of it was spent solely in the constructor of SimpleDateFormat. It created and then threw away a new one every time it had to parse a date. Whew! 

“Great,” you think, “I’ll just create one, static instance, slap it in a field in a DateUtils helper class and life will be good.” 

Well, more precisely, life will be good about 97% of the time. A few days after you roll that code into production you’ll discover the second cool fact that’s good to know: SimpleDateFormat is not thread safe. Your code will work just fine most of the time and all of your regression tests will probably pass, but once your system gets under a production load you’ll see the occasional exception. 

“Fine,” you think, “I’ll just slap a ’synchronized’ around my use of that one, static instance.” 

Ok, fine, you could do that and you’d be more or less ok, but the problem is that you’ve now taken a very common operation (date formatting and parsing) and crammed all of your otherwise-lovely, super-parallel application through a single pipe to get it done.


     澶ц嚧鎰忔濓細Tim Cull紕板埌涓涓猄impleDateFormat甯︽潵鐨勪弗閲嶇殑鎬ц兘闂錛岃闂涓昏鏈塖impleDateFormat寮曞彂錛屽垱寤轟竴涓猄impleDateFormat瀹炰緥鐨勫紑閿姣旇緝鏄傝吹錛岃В鏋愬瓧絎︿覆鏃墮棿鏃墮綣佸垱寤虹敓鍛藉懆鏈熺煭鏆傜殑瀹炰緥瀵艱嚧鎬ц兘浣庝笅銆傚嵆浣垮皢SimpleDateFormat瀹氫箟涓洪潤鎬佺被鍙橀噺錛岃矊浼艱兘瑙e喅榪欎釜闂錛屼絾鏄疭impleDateFormat鏄潪綰跨▼瀹夊叏鐨勶紝鍚屾牱瀛樺湪闂錛屽鏋滅敤‘synchronized’綰跨▼鍚屾鍚屾牱闈復闂錛屽悓姝ュ鑷存ц兘涓嬮檷錛堢嚎紼嬩箣闂村簭鍒楀寲鐨勮幏鍙朣impleDateFormat瀹炰緥錛夈?/p>

    Tim Cull浣跨敤Threadlocal瑙e喅浜嗘闂錛屽浜庢瘡涓嚎紼婼impleDateFormat涓嶅瓨鍦ㄥ獎鍝嶄粬浠箣闂村崗浣滅殑鐘舵侊紝涓烘瘡涓嚎紼嬪垱寤轟竴涓猄impleDateFormat鍙橀噺鐨勬嫹璐濇垨鑰呭彨鍋氬壇鏈紝浠g爜濡備笅錛?/p>


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 浣跨敤ThreadLocal浠ョ┖闂存崲鏃墮棿瑙e喅SimpleDateFormat綰跨▼瀹夊叏闂銆?
* @author
*
*/
public class DateUtil {
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
@SuppressWarnings("rawtypes")
private static ThreadLocal threadLocal = new ThreadLocal() {
protected synchronized Object initialValue() {
return new SimpleDateFormat(DATE_FORMAT);
}
};
public static DateFormat getDateFormat() {
return (DateFormat) threadLocal.get();
}
public static Date parse(String textDate) throws ParseException {
return getDateFormat().parse(textDate);
}
}


   鍒涘緩涓涓猅hreadLocal綾誨彉閲忥紝榪欓噷鍒涘緩鏃剁敤浜嗕竴涓尶鍚嶇被錛岃鐩栦簡initialValue鏂規硶錛屼富瑕佷綔鐢ㄦ槸鍒涘緩鏃跺垵濮嬪寲瀹炰緥銆備篃鍙互閲囩敤涓嬮潰鏂瑰紡鍒涘緩錛?/p>


//絎竴嬈¤皟鐢╣et灝嗚繑鍥瀗ull
private static ThreadLocal threadLocal = new ThreadLocal()錛?
//鑾峰彇綰跨▼鐨勫彉閲忓壇鏈紝濡傛灉涓嶈鐩杋nitialValue錛岀涓嬈et榪斿洖null錛屾晠闇瑕佸垵濮嬪寲涓涓猄impleDateFormat錛屽茍set鍒皌hreadLocal涓?
public static DateFormat getDateFormat()
{
DateFormat df = (DateFormat) threadLocal.get();
if(df==null){
df = new SimpleDateFormat(DATE_FORMAT)
threadLocal.set(df);
}
return df;
}


   鎴戜滑鐪嬩笅鎴戜滑瑕嗙洊鐨刬nitialValue鏂規硶錛?/p>


protected T initialValue() {
return null;//鐩存帴榪斿洖null
}






絀虹櫧 2011-05-10 21:01 鍙戣〃璇勮
]]>
鎺㈢┒Struts2榪愯鏈哄埗錛歋trutsPrepareAndExecuteFilter 婧愮爜鍓栨瀽http://www.tkk7.com/niumd/archive/2011/05/10/349959.html絀虹櫧絀虹櫧Tue, 10 May 2011 12:58:00 GMThttp://www.tkk7.com/niumd/archive/2011/05/10/349959.htmlhttp://www.tkk7.com/niumd/comments/349959.htmlhttp://www.tkk7.com/niumd/archive/2011/05/10/349959.html#Feedback0http://www.tkk7.com/niumd/comments/commentRss/349959.htmlhttp://www.tkk7.com/niumd/services/trackbacks/349959.html

  浣滆咃細niumd

  blog錛?a mce_href="/">http://ari.iteye.com

 涓銆佹榪?/strong>

     Struts2鐨勬牳蹇冩槸涓涓狥ilter錛孉ction鍙互鑴辯web瀹瑰櫒錛岄偅涔堟槸浠涔堣http璇鋒眰鍜宎ction鍏寵仈鍦ㄤ竴璧風殑錛屼笅闈㈡垜浠繁鍏ユ簮鐮佹潵鍒嗘瀽涓婼truts2鏄浣曞伐浣滅殑銆?/p>

FilterDispatcher API 鍐欓亾
Deprecated. Since Struts 2.1.3, use StrutsPrepareAndExecuteFilter instead or StrutsPrepareFilter and StrutsExecuteFilter if needing using the ActionContextCleanUp filter in addition to this one


     閴翠簬甯歌鎯呭喌瀹樻柟鎺ㄨ崘浣跨敤StrutsPrepareAndExecuteFilter鏇夸唬FilterDispatcher錛屾垜浠鏂囧皢鍓栨瀽StrutsPrepareAndExecuteFilter錛屽叾鍦ㄥ伐紼嬩腑浣滀負涓涓狥ilter閰嶇疆鍦╳eb.xml涓紝閰嶇疆濡備笅錛?/p>

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


浜屻佹簮鐮佸睘鎬ф柟娉曠畝浠?/strong>

    涓嬮潰鎴戜滑鐮旂┒涓婼trutsPrepareAndExecuteFilter婧愮爜錛岀被鐨勪富瑕佷俊鎭涓嬶細


灞炴ф憳瑕?/strong>
protected  List<Pattern> excludedPatterns 
           
protected  ExecuteOperations execute 
           
protected  PrepareOperations prepare 
           


    StrutsPrepareAndExecuteFilter涓庢櫘閫氱殑Filter騫舵棤鍖哄埆錛屾柟娉曢櫎緇ф壙鑷狥ilter澶栵紝浠呮湁涓涓洖璋冩柟娉曪紝絎笁閮ㄥ垎鎴戜滑灝嗘寜鐓ilter鏂規硶璋冪敤欏哄簭錛岀敱init鈥?gt;doFilter鈥?gt;destroy欏哄簭鍦板垎鏋愭簮鐮併?/p>
鏂規硶鎽樿
 void destroy() 
           緇ф壙鑷狥ilter錛岀敤浜庤祫婧愰噴鏀?/td>
 void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
           緇ф壙鑷狥ilter錛屾墽琛屾柟娉?/td>
 void init(FilterConfig filterConfig) 
           緇ф壙鑷狥ilter錛屽垵濮嬪寲鍙傛暟
protected  void postInit(Dispatcher dispatcher, FilterConfig filterConfig) 
          Callback for post initialization錛堜竴涓┖鐨勬柟娉曪紝鐢ㄤ簬鏂規硶鍥炶皟鍒濆鍖栵級


涓夈佹簮鐮佸墫鏋?nbsp;   


    1銆乮nit鏂規硶

         init鏄疐ilter絎竴涓繍琛岀殑鏂規硶錛屾垜浠湅涓媠truts2鐨勬牳蹇僃ilter鍦ㄨ皟鐢╥nit鏂規硶鍒濆鍖栨椂鍋氬摢浜涘伐浣滐細

 public void init(FilterConfig filterConfig) throws ServletException {
InitOperations init = new InitOperations();
try {
//灝佽filterConfig錛屽叾涓湁涓富瑕佹柟娉昰etInitParameterNames灝嗗弬鏁板悕瀛椾互String鏍煎紡瀛樺偍鍦↙ist涓?
FilterHostConfig config = new FilterHostConfig(filterConfig);
// 鍒濆鍖杝truts鍐呴儴鏃ュ織
init.initLogging(config);
//鍒涘緩dispatcher 錛屽茍鍒濆鍖栵紝榪欓儴鍒嗕笅闈㈡垜浠噸鐐瑰垎鏋愶紝鍒濆鍖栨椂鍔犺澆閭d簺璧勬簮
Dispatcher dispatcher = init.initDispatcher(config);
init.initStaticContentLoader(config, dispatcher);
//鍒濆鍖栫被灞炴э細prepare 銆乪xecute
prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);
execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);
this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);
//鍥炶皟絀虹殑postInit鏂規硶
postInit(dispatcher, filterConfig);
} finally {
init.cleanup();
}
}


   棣栧厛鐪嬩笅FilterHostConfig 錛屾簮鐮佸涓嬶細


public class FilterHostConfig implements HostConfig {
private FilterConfig config;
/**
*鏋勯犲嚱鏁?
*/
public FilterHostConfig(FilterConfig config) {
this.config = config;
}
/**
*  鏍規嵁init-param閰嶇疆鐨刾aram-name鑾峰彇param-value鐨勫?
*/
public String getInitParameter(String key) {
return config.getInitParameter(key);
}
/**
*  榪斿洖鍒濆鍖栧弬鏁板悕鐨凩ist
*/
public Iterator<String> getInitParameterNames() {
return MakeIterator.convert(config.getInitParameterNames());
}
public ServletContext getServletContext() {
return config.getServletContext();
}
}

   鍙湁鐭煭鐨勫嚑琛屼唬鐮侊紝getInitParameterNames鏄繖涓被鐨勬牳蹇冿紝灝咶ilter鍒濆鍖栧弬鏁板悕縐版湁鏋氫婦綾誨瀷杞負Iterator銆傛綾葷殑涓昏浣滀負鏄filterConfig 灝佽銆?/p>



    閲嶇偣鏉ヤ簡錛屽垱寤哄茍鍒濆鍖朌ispatcher     

 public Dispatcher initDispatcher( HostConfig filterConfig ) {
Dispatcher dispatcher = createDispatcher(filterConfig);
dispatcher.init();
return dispatcher;
}

     鍒涘緩Dispatcher錛屼細璇誨彇 filterConfig 涓殑閰嶇疆淇℃伅錛屽皢閰嶇疆淇℃伅瑙f瀽鍑烘潵錛屽皝瑁呮垚涓轟竴涓狹ap錛岀劧鍚庢牴緇漵ervlet涓婁笅鏂囧拰鍙傛暟Map鏋勯燚ispatcher 錛?/p>

private Dispatcher createDispatcher( HostConfig filterConfig ) {
Map<String, String> params = new HashMap<String, String>();
for ( Iterator e = filterConfig.getInitParameterNames(); e.hasNext(); ) {
String name = (String) e.next();
String value = filterConfig.getInitParameter(name);
params.put(name, value);
}
return new Dispatcher(filterConfig.getServletContext(), params);
}

  Dispatcher鍒濆鍖栵紝鍔犺澆struts2鐨勭浉鍏抽厤緗枃浠訛紝灝嗘寜鐓ч『搴忛愪竴鍔犺澆錛歞efault.properties錛宻truts-default.xml,struts-plugin.xml,struts.xml錛?#8230;…


/**
*鍒濆鍖栬繃紼嬩腑渚濇鍔犺澆濡備笅閰嶇疆鏂囦歡
*/
public void init() {
if (configurationManager == null) {
configurationManager = new ConfigurationManager(BeanSelectionProvider.DEFAULT_BEAN_NAME);
}
try {
//鍔犺澆org/apache/struts2/default.properties
init_DefaultProperties(); // [1]
//鍔犺澆struts-default.xml,struts-plugin.xml,struts.xml
init_TraditionalXmlConfigurations(); // [2]
init_LegacyStrutsProperties(); // [3]
//鐢ㄦ埛鑷繁瀹炵幇鐨凜onfigurationProviders綾?
init_CustomConfigurationProviders(); // [5]
//Filter鐨勫垵濮嬪寲鍙傛暟
init_FilterInitParameters() ; // [6]
init_AliasStandardObjects() ; // [7]
Container container = init_PreloadConfiguration();
container.inject(this);
init_CheckConfigurationReloading(container);
init_CheckWebLogicWorkaround(container);
if (!dispatcherListeners.isEmpty()) {
for (DispatcherListener l : dispatcherListeners) {
l.dispatcherInitialized(this);
}
}
} catch (Exception ex) {
if (LOG.isErrorEnabled())
LOG.error("Dispatcher initialization failed", ex);
throw new StrutsException(ex);
}
}


   鍒濆鍖杁efault.properties錛屽叿浣撶殑鍒濆鍖栨搷浣滃湪DefaultPropertiesProvider綾諱腑

  

 private void init_DefaultProperties() {
configurationManager.addConfigurationProvider(new DefaultPropertiesProvider());
}

    

   涓嬮潰鎴戜滑鐪嬩笅DefaultPropertiesProvider綾繪簮鐮侊細


public void register(ContainerBuilder builder, LocatableProperties props)
throws ConfigurationException {
Settings defaultSettings = null;
try {
defaultSettings = new PropertiesSettings("org/apache/struts2/default");
} catch (Exception e) {
throw new ConfigurationException("Could not find or error in org/apache/struts2/default.properties", e);
}
loadSettings(props, defaultSettings);
}


   鍏朵粬鐨勬垜浠啀嬈$渷鐣ワ紝澶у鍙互嫻忚涓嬪悇涓垵濮嬪寲鎿嶄綔閮藉姞杞戒簡閭d簺鏂囦歡


3銆乨oFilter鏂規硶

     doFilter鏄繃婊ゅ櫒鐨勬墽琛屾柟娉曪紝瀹冩嫤鎴彁浜ょ殑HttpServletRequest璇鋒眰錛孒ttpServletResponse鍝嶅簲錛屼綔涓簊trtus2鐨勬牳蹇冩嫤鎴櫒錛屽湪doFilter閲岄潰鍒板簳鍋氫簡鍝簺宸ヤ綔錛屾垜浠皢閫愯瑙h鍏舵簮鐮侊紝婧愮爜濡備笅錛?/p>


    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
//鐖剁被鍚戝瓙綾昏漿錛氬己杞負http璇鋒眰銆佸搷搴?
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
try {
//璁劇疆緙栫爜鍜屽浗闄呭寲
prepare.setEncodingAndLocale(request, response);
//鍒涘緩Action涓婁笅鏂囷紙閲嶇偣錛?
prepare.createActionContext(request, response);
prepare.assignDispatcherToThread();
if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
chain.doFilter(request, response);
} else {
request = prepare.wrapRequest(request);
ActionMapping mapping = prepare.findActionMapping(request, response, true);
if (mapping == null) {
boolean handled = execute.executeStaticResourceRequest(request, response);
if (!handled) {
chain.doFilter(request, response);
}
} else {
execute.executeAction(request, response, mapping);
}
}
} finally {
prepare.cleanupRequest(request);
}
}


    setEncodingAndLocale璋冪敤浜哾ispatcher鏂規硶鐨刾repare鏂規硶錛?/p>


/**
* Sets the request encoding and locale on the response
*/
public void setEncodingAndLocale(HttpServletRequest request, HttpServletResponse response) {
dispatcher.prepare(request, response);
}


   涓嬮潰鎴戜滑鐪嬩笅prepare鏂規硶錛岃繖涓柟娉曞緢綆鍗曞彧鏄緗簡encoding 銆乴ocale 錛屽仛鐨勫彧鏄竴浜涜緟鍔╃殑宸ヤ綔錛?/p>

public void prepare(HttpServletRequest request, HttpServletResponse response) {
String encoding = null;
if (defaultEncoding != null) {
encoding = defaultEncoding;
}
Locale locale = null;
if (defaultLocale != null) {
locale = LocalizedTextUtil.localeFromString(defaultLocale, request.getLocale());
}
if (encoding != null) {
try {
request.setCharacterEncoding(encoding);
} catch (Exception e) {
LOG.error("Error setting character encoding to '" + encoding + "' - ignoring.", e);
}
}
if (locale != null) {
response.setLocale(locale);
}
if (paramsWorkaroundEnabled) {
request.getParameter("foo"); // simply read any parameter (existing or not) to "prime" the request
}
}


   Action涓婁笅鏂囧垱寤猴紙閲嶇偣錛?/strong>

       ActionContext鏄竴涓鍣紝榪欎釜瀹規槗涓昏瀛樺偍request銆乻ession銆乤pplication銆乸arameters絳夌浉鍏充俊鎭?ActionContext鏄竴涓嚎紼嬬殑鏈湴鍙橀噺錛岃繖鎰忓懗鐫涓嶅悓鐨刟ction涔嬮棿涓嶄細鍏變韓ActionContext錛屾墍浠ヤ篃涓嶇敤鑰冭檻綰跨▼瀹夊叏闂銆傚叾瀹炶川鏄竴涓狹ap錛宬ey鏄爣紺簉equest銆乻ession銆?#8230;…鐨勫瓧絎︿覆錛屽兼槸鍏跺搴旂殑瀵硅薄錛?/p>

static ThreadLocal actionContext = new ThreadLocal();
Map<String, Object> context;

 
   涓嬮潰鎴戜滑鐪嬩笅濡備綍鍒涘緩action涓婁笅鏂囩殑錛屼唬鐮佸涓嬶細


/**
*鍒涘緩Action涓婁笅鏂囷紝鍒濆鍖杢hread local
*/
public ActionContext createActionContext(HttpServletRequest request, HttpServletResponse response) {
ActionContext ctx;
Integer counter = 1;
Integer oldCounter = (Integer) request.getAttribute(CLEANUP_RECURSION_COUNTER);
if (oldCounter != null) {
counter = oldCounter + 1;
}
//娉ㄦ剰姝ゅ鏄粠ThreadLocal涓幏鍙栨ActionContext鍙橀噺
ActionContext oldContext = ActionContext.getContext();
if (oldContext != null) {
// detected existing context, so we are probably in a forward
ctx = new ActionContext(new HashMap<String, Object>(oldContext.getContextMap()));
} else {
ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
stack.getContext().putAll(dispatcher.createContextMap(request, response, null, servletContext));
//stack.getContext()榪斿洖鐨勬槸涓涓狹ap<String錛孫bject>錛屾牴鎹Map鏋勯犱竴涓狝ctionContext
ctx = new ActionContext(stack.getContext());
}
request.setAttribute(CLEANUP_RECURSION_COUNTER, counter);
//灝咥ctionContext瀛樺ThreadLocal
ActionContext.setContext(ctx);
return ctx;
}


    涓婇潰浠g爜涓璬ispatcher.createContextMap錛屽浣曞皝瑁呯浉鍏沖弬鏁幫細


public Map<String,Object> createContextMap(HttpServletRequest request, HttpServletResponse response,
ActionMapping mapping, ServletContext context) {
// request map wrapping the http request objects
Map requestMap = new RequestMap(request);
// parameters map wrapping the http parameters.  ActionMapping parameters are now handled and applied separately
Map params = new HashMap(request.getParameterMap());
// session map wrapping the http session
Map session = new SessionMap(request);
// application map wrapping the ServletContext
Map application = new ApplicationMap(context);
//requestMap銆乸arams銆乻ession絳塎ap灝佽鎴愪負涓涓笂涓嬫枃Map錛岄愪釜璋冪敤浜唌ap.put(Map p).
Map<String,Object> extraContext = createContextMap(requestMap, params, session, application, request, response, context);
if (mapping != null) {
extraContext.put(ServletActionContext.ACTION_MAPPING, mapping);
}
return extraContext;
}


 鎴戜滑綆鍗曠湅涓婻equestMap錛屽叾浠栫殑鐪佺暐銆俁equestMap綾誨疄鐜頒簡鎶借薄Map錛屾晠鍏舵湰韜槸涓涓狹ap錛屼富瑕佹柟娉曞疄鐜幫細

//map鐨刧et瀹炵幇
public Object get(Object key) {
return request.getAttribute(key.toString());
}
//map鐨刾ut瀹炵幇
public Object put(Object key, Object value) {
Object oldValue = get(key);
entries = null;
request.setAttribute(key.toString(), value);
return oldValue;
}


   涓嬮潰鏄簮鐮佸睍紺轟簡濡備綍鎵цAction鎺у埗鍣細


public void executeAction(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws ServletException {
dispatcher.serviceAction(request, response, servletContext, mapping);
}
public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,
ActionMapping mapping) throws ServletException {
//灝佽鎵ц鐨勪笂涓嬫枃鐜錛屼富瑕佽鐩稿叧淇℃伅瀛樺偍鍏ap
Map<String, Object> extraContext = createContextMap(request, response, mapping, context);
// If there was a previous value stack, then create a new copy and pass it in to be used by the new Action
ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
boolean nullStack = stack == null;
if (nullStack) {
ActionContext ctx = ActionContext.getContext();
if (ctx != null) {
stack = ctx.getValueStack();
}
}
if (stack != null) {
extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));
}
String timerKey = "Handling request from Dispatcher";
try {
UtilTimerStack.push(timerKey);
//鑾峰彇鍛藉悕絀洪棿
String namespace = mapping.getNamespace();
//鑾峰彇action閰嶇疆鐨刵ame灞炴?
String name = mapping.getName();
//鑾峰彇action閰嶇疆鐨刴ethod灞炴?
String method = mapping.getMethod();
Configuration config = configurationManager.getConfiguration();
//鏍規嵁鎵ц涓婁笅鏂囧弬鏁幫紝鍛藉悕絀洪棿錛屽悕縐扮瓑鍒涘緩鐢ㄦ埛鑷畾涔堿ction鐨勪唬鐞嗗璞?
ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
namespace, name, method, extraContext, true, false);
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());
// if the ActionMapping says to go straight to a result, do it!
//鎵цexecute鏂規硶錛屽茍杞悜緇撴灉
if (mapping.getResult() != null) {
Result result = mapping.getResult();
result.execute(proxy.getInvocation());
} else {
proxy.execute();
}
// If there was a previous value stack then set it back onto the request
if (!nullStack) {
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);
}
} catch (ConfigurationException e) {
// WW-2874 Only log error if in devMode
if(devMode) {
String reqStr = request.getRequestURI();
if (request.getQueryString() != null) {
reqStr = reqStr + "?" + request.getQueryString();
}
LOG.error("Could not find action or result\n" + reqStr, e);
}
else {
LOG.warn("Could not find action or result", e);
}
sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);
} catch (Exception e) {
sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} finally {
UtilTimerStack.pop(timerKey);
}
}


   鏂囦腑瀵瑰浣曡В鏋怱truts.xml錛屽浣曞皢URL涓巃ction鏄犲皠鍖歸厤涓哄垎鏋愶紝鏈夐渶瑕佺殑鎴戝悗緇ˉ鍏紝鍥犱負StrutsXmlConfigurationProvider緇ф壙XmlConfigurationProvider錛屽茍鍦╮egister鏂規硶鍥炶皟鐖剁被鐨剅egister錛屾湁鍏磋叮鐨勫彲浠ユ繁鍏ラ槄璇諱笅涓媂mlConfigurationProvider婧愮爜錛?/p>


 public void register(ContainerBuilder containerBuilder, LocatableProperties props) throws ConfigurationException {
if (servletContext != null && !containerBuilder.contains(ServletContext.class)) {
containerBuilder.factory(ServletContext.class, new Factory<ServletContext>() {
public ServletContext create(Context context) throws Exception {
return servletContext;
}
});
}
//璋冪敤鐖剁被鐨剅egister錛屽叧閿偣鎵鍦?
super.register(containerBuilder, props);
}



     struts2-core-2.2.1.jar鍖呬腑struts-2.1.7.dtd瀵逛簬Action鐨勫畾涔夊涓嬶細

<!ELEMENT action (param|result|interceptor-ref|exception-mapping)*>
<!ATTLIST action
name CDATA #REQUIRED
class CDATA #IMPLIED
method CDATA #IMPLIED
converter CDATA #IMPLIED
>

    浠庝笂榪癉TD涓彲瑙丄ction鍏冪礌鍙互鍚湁name 銆乧lass 銆乵ethod 銆乧onverter 灞炴с?/p>


   XmlConfigurationProvider瑙f瀽struts.xml閰嶇疆鐨凙ction鍏冪礌錛?/p>

   protected void addAction(Element actionElement, PackageConfig.Builder packageContext) throws ConfigurationException {
String name = actionElement.getAttribute("name");
String className = actionElement.getAttribute("class");
String methodName = actionElement.getAttribute("method");
Location location = DomHelper.getLocationObject(actionElement);
if (location == null) {
LOG.warn("location null for " + className);
}
//methodName should be null if it's not set
methodName = (methodName.trim().length() > 0) ? methodName.trim() : null;
// if there isnt a class name specified for an <action/> then try to
// use the default-class-ref from the <package/>
if (StringUtils.isEmpty(className)) {
// if there is a package default-class-ref use that, otherwise use action support
/* if (StringUtils.isNotEmpty(packageContext.getDefaultClassRef())) {
className = packageContext.getDefaultClassRef();
} else {
className = ActionSupport.class.getName();
}*/
} else {
if (!verifyAction(className, name, location)) {
if (LOG.isErrorEnabled())
LOG.error("Unable to verify action [#0] with class [#1], from [#2]", name, className, location.toString());
return;
}
}
Map<String, ResultConfig> results;
try {
results = buildResults(actionElement, packageContext);
} catch (ConfigurationException e) {
throw new ConfigurationException("Error building results for action " + name + " in namespace " + packageContext.getNamespace(), e, actionElement);
}
List<InterceptorMapping> interceptorList = buildInterceptorList(actionElement, packageContext);
List<ExceptionMappingConfig> exceptionMappings = buildExceptionMappings(actionElement, packageContext);
ActionConfig actionConfig = new ActionConfig.Builder(packageContext.getName(), name, className)
.methodName(methodName)
.addResultConfigs(results)
.addInterceptors(interceptorList)
.addExceptionMappings(exceptionMappings)
.addParams(XmlHelper.getParams(actionElement))
.location(location)
.build();
packageContext.addActionConfig(name, actionConfig);
if (LOG.isDebugEnabled()) {
LOG.debug("Loaded " + (StringUtils.isNotEmpty(packageContext.getNamespace()) ? (packageContext.getNamespace() + "/") : "") + name + " in '" + packageContext.getName() + "' package:" + actionConfig);
}
}



     宸ヤ綔涓笉娑夊強Struts2錛屾湰鍛ㄥ伐浣滄湁涓?澶╃殑絀烘。鏈燂紝紼嶅井鐪嬩簡涓媠truts2鐨勬枃妗o紝鍐欎簡涓猟emo錛屼粠婧愮爜鐨勮搴︾爺絀朵簡涓嬭繍琛屽師鐞嗭紝濡傛湁鍒嗘瀽涓嶅綋璇鋒寚鍑猴紝鎴戝悗緇愭瀹屽杽鏇存錛屽ぇ瀹跺叡鍚屾彁楂樸?/p>




絀虹櫧 2011-05-10 20:58 鍙戣〃璇勮
]]>
NetBean6瀛椾綋閰嶇疆http://www.tkk7.com/niumd/archive/2008/09/07/227537.html絀虹櫧絀虹櫧Sun, 07 Sep 2008 05:46:00 GMThttp://www.tkk7.com/niumd/archive/2008/09/07/227537.htmlhttp://www.tkk7.com/niumd/comments/227537.htmlhttp://www.tkk7.com/niumd/archive/2008/09/07/227537.html#Feedback2http://www.tkk7.com/niumd/comments/commentRss/227537.htmlhttp://www.tkk7.com/niumd/services/trackbacks/227537.html闃呰鍏ㄦ枃

絀虹櫧 2008-09-07 13:46 鍙戣〃璇勮
]]>
Spring涔婤eanFactory涓嶢pplicationConText鍖哄埆http://www.tkk7.com/niumd/archive/2008/06/22/209873.html絀虹櫧絀虹櫧Sun, 22 Jun 2008 10:34:00 GMThttp://www.tkk7.com/niumd/archive/2008/06/22/209873.htmlhttp://www.tkk7.com/niumd/comments/209873.htmlhttp://www.tkk7.com/niumd/archive/2008/06/22/209873.html#Feedback0http://www.tkk7.com/niumd/comments/commentRss/209873.htmlhttp://www.tkk7.com/niumd/services/trackbacks/209873.htmlimport org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class XmlConfigWithBeanFactory {

    
public static void main(String[] args) {
        XmlBeanFactory factory 
= new XmlBeanFactory(new FileSystemResource(
                
"build/beans.xml"));

    }

}

    浣跨敤ApplicationConText浠巟ml閰嶇疆鏂囦歡鍔犺澆bean:
public class XmlConfigWithApplication{

    
public static void main(String[] args){
        ApplicationContext application 
= new ClassPathXmlApplicationContext(beans.xml"));
         application.getBean("BeanName");
    }

}

    ApplicationContext鍜孊eanFacotry鐩告瘮,鎻愪緵浜嗘洿澶氱殑鎵╁睍鍔熻兘錛屼絾鍏朵富瑕佸尯鍒湪浜庡悗鑰呮槸寤惰繜鍔犺澆,濡傛灉Bean鐨勬煇涓涓睘鎬ф病鏈夋敞鍏ワ紝BeanFacotry鍔犺澆鍚庯紝鐩磋嚦絎竴嬈′嬌鐢ㄨ皟鐢╣etBean鏂規硶鎵嶄細鎶涘嚭寮傚父錛涜孉pplicationContext鍒欏湪鍒濆鍖栬嚜韜槸媯楠岋紝榪欐牱鏈夊埄浜庢鏌ユ墍渚濊禆灞炴ф槸鍚︽敞鍏ワ紱鎵浠ラ氬父鎯呭喌涓嬫垜浠夋嫨浣跨敤ApplicationContext.

絀虹櫧 2008-06-22 18:34 鍙戣〃璇勮
]]>
浣跨敤Xfire寮鍙慦ebServicehttp://www.tkk7.com/niumd/archive/2008/06/20/209404.html絀虹櫧絀虹櫧Fri, 20 Jun 2008 04:10:00 GMThttp://www.tkk7.com/niumd/archive/2008/06/20/209404.htmlhttp://www.tkk7.com/niumd/comments/209404.htmlhttp://www.tkk7.com/niumd/archive/2008/06/20/209404.html#Feedback2http://www.tkk7.com/niumd/comments/commentRss/209404.htmlhttp://www.tkk7.com/niumd/services/trackbacks/209404.html 涓嬮潰鏄垜浠璁$殑webservice鐨勬帴鍙?
 1package com.test.service;
 2
 3import java.util.List;
 4
 5public interface IPerson {
 6    //鏍規嵁鐢ㄦ埛鍚嶈幏鍙栧瘑鐮?/span>
 7    public String getPassword(String name);
 8    //鏍規嵁鐢ㄦ埛鍚嶈幏鍙朠erson瀵硅薄
 9    public Person getPersonByName();
10    //鑾峰彇鍏ㄩ儴鎴愬憳
11    public List<Person> getAllPerson();
12}

鍏朵腑鏈変笁涓柟娉曞寘鍚簡浼犻?String,Object,List闆嗗悎;
2,榪欓噷鎴戜滑瀹炵幇鎺ュ彛涓畾涔夌殑涓氬姟閫昏緫
package com.test.service;

import java.util.LinkedList;
import java.util.List;

public class PersonImpl implements IPerson {
    
    
    
public String getPassword(String name) {
        
        
return "Password";
    }


    
public Person getPersonByName() {
        
        
return new Person("ObjectName","ObjectPass");
    }


    
public java.util.List<Person> getAllPerson(){
        
        List list 
= new LinkedList();
        list.add(
new Person("One","PassOne"));
        list.add(
new Person("Two","PassTwo"));
        list.add(
new Person("Three","PassThree"));
        
return list;
    }

}

鍦ㄥ疄闄呭簲鐢ㄤ腑姣旇緝澶嶆潅,鍙兘鐢ㄨ皟鐢ㄦ寔涔呭眰鐨凞ao,榪斿洖闇瑕佺殑緇撴灉,榪欓噷鎴戜滑鐩存帴鍒涘緩涓涓ā鎷熸暟鎹?涓嬮潰鏄疄鐜扮被涓敤鍒扮殑瀵硅薄
 1package com.test.service;
 2
 3public class Person {
 4    private String name;
 5    private String password;
 6    
 7    public Person() {
 8        super();
 9    }

10    public Person(String name, String password){
11        super();
12        this.name = name;
13        this.password = password;
14    }

15    public String getPassword(){
16        return password;
17    }

18    public void setPassword(String password){
19        this.password = password;
20    }

21}

22

3,緙栧啓XFire瑕佹眰鐨刉ebSevice瀹氫箟鎻忚堪鏂囦歡錛屽涓嬶細
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xfire.codehaus.org/config/1.0">

    
<service>
        
<name>Person</name>
        
<serviceClass>com.test.service.IPerson</serviceClass>
        
<implementationClass>
            com.test.service.PersonImpl
        
</implementationClass>
        
<style>wrapped</style>
        
<use>literal</use>
        
<scope>application</scope>
    
</service></beans>
鏈枃浠剁殑鏀劇疆浣嶇疆寰堝叧閿?姝ゆ枃浠舵斁鍦╯rc/META-INF/xfire/services.xml錛屽鏋滀嬌鐢∕yEclipse鏂板緩鐨勪笉鏄痺ebapplication,鑰屾槸webservice欏圭洰,榪欎竴姝ュ氨鐪佸幓鑷繁緙栧啓浜?緙栬瘧鏃朵細鑷姩緙栬瘧鍒癱lasses鐨勭浉搴旂洰褰曚笅闈€倃eb.z
5,緙栬瘧xml,瀹氫箟XfireConfigableServlet
 1<?xml version="1.0" encoding="UTF-8"?>
 2<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 3  <servlet>
 4    <servlet-name>XFireServlet</servlet-name>
 5    <servlet-class>org.codehaus.xfire.transport.http.XFireConfigurableServlet</servlet-class>
 6    <load-on-startup>0</load-on-startup>
 7  </servlet>
 8  <servlet-mapping>
 9    <servlet-name>XFireServlet</servlet-name>
10    <url-pattern>/services/*</url-pattern>
11  </servlet-mapping>
12  <welcome-file-list>
13    <welcome-file>index.jsp</welcome-file>
14  </welcome-file-list>
15</web-app>
16
17
鎵鏈夌殑宸ヤ綔閮藉凡緇忎綔瀹岋紝鎺ヤ笅鏉ュ湪閮ㄧ講鍦╰omcate涓嬶紝鍚姩鏈嶅姟鍣紝鍦ㄥ湴鍧鏍忛敭鍏ワ細http://127.0.0.1:8080/MyWebService/srevice/Person?wsdl
濡傛灉鍑虹幇xml鎻忚堪鏂囦歡灝辨垚鍔熶簡錛?br />



絀虹櫧 2008-06-20 12:10 鍙戣〃璇勮
]]>
主站蜘蛛池模板: 女人18毛片a级毛片免费| 一本色道久久综合亚洲精品蜜桃冫 | 真人无码作爱免费视频| 久久久亚洲精品国产| 亚洲?V无码成人精品区日韩| 97免费人妻无码视频| 久久青草免费91线频观看不卡| 日韩在线观看免费| 亚洲成a∨人片在无码2023| 亚洲一本综合久久| 亚洲欧洲日产国码无码网站| 又大又粗又爽a级毛片免费看| 天天拍拍天天爽免费视频| 1000部禁片黄的免费看| 国产一精品一AV一免费| 无码免费又爽又高潮喷水的视频 | 久久精品视频免费播放| 三级毛片在线免费观看| 九九综合VA免费看| 亚洲av纯肉无码精品动漫| 亚洲AV成人一区二区三区在线看 | 57pao国产成永久免费视频| 中文字幕无码毛片免费看| 一区二区三区免费看| 欧洲亚洲综合一区二区三区| 亚洲中文字幕久久久一区| 国产成人精品日本亚洲直接| 亚洲天堂中文字幕在线观看| 在线观看亚洲一区二区| 久久精品国产亚洲AV大全| 亚洲国产精品一区二区久久| 好看的亚洲黄色经典| 亚洲妇熟XXXX妇色黄| 亚洲国产另类久久久精品| 亚洲福利在线视频| 日韩亚洲AV无码一区二区不卡 | 久久永久免费人妻精品下载| 久艹视频在线免费观看| 99在线观看免费视频| 午夜免费1000部| 五月婷婷综合免费|