1. 程式人生 > >線程異步調用實例

線程異步調用實例

exce requires logs support .com except cPage spring ans

更新content時更新Lucene的索引

Content newContent = contentService.update(content);
afterContentStatusChange(newContent, ContentStatusChangeThread.OPERATE_UPDATE);

private void afterContentStatusChange(Content content, Short operate){

  ContentStatusChangeThread afterThread = new ContentStatusChangeThread(
                content,operate,
                new LuceneListener());
  afterThread.start();
}
package com.jeecms.cms.staticpage;

import java.util.List;
import java.util.Map;

import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.Assert;
import org.hibernate.Session; import org.springframework.orm.hibernate4.HibernateTransactionManager; import com.jeecms.cms.entity.main.Content; import com.jeecms.cms.manager.main.ContentMng; import com.jeecms.cms.service.ContentListener; import com.jeecms.cms.web.ApplicationContextUtil; public class
ContentStatusChangeThread extends Thread { public static Short OPERATE_ADD=1; public static Short OPERATE_UPDATE=2; public static Short OPERATE_DEL=3; private Content content; //=1保存 =2修改 =3刪除 private Short operateType; private LuceneListener listener;public ContentStatusChangeThread(Content content,Short operateType,LuceneListener listener) { super(); this.content=content; this.operateType=operateType; this.listener=listener; } @Override public void run() { HibernateTransactionManager transactionManager = (HibernateTransactionManager) ApplicationContextUtil
            .getBean("transactionManager"); DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔離級別,開啟新事務 TransactionStatus status = transactionManager.getTransaction(def); // 獲得事務狀態 try { //邏輯代碼 if(operateType==1){ afterSave(content); }else if(operateType==2){ ContentMng contentMng=(ContentMng) ApplicationContextUtil.getBean("contentMng"); content=contentMng.findById(content.getId()); afterChange(content, listener); }else if(operateType==3){ afterDelete(content); } transactionManager.commit(status); } catch (Exception e) { transactionManager.rollback(status); } } private void afterSave(Content content) { if (listener != null) { listener.afterSave(content); } } private void afterChange(Content content, LuceneListener listener) { if (listener != null) { listener.afterChange(content); } } private void afterDelete(Content content) { if (listener != null) { listener.afterDelete(content); } } }
@Override
public void afterChange(Content content) {
    luceneContentService.updateIndex(content);
}

線程異步調用實例