Java异步存储数据线程

版权声明:本文为博主原创文章,未经博主允许欢迎转载。 https://blog.csdn.net/LANGZI7758521/article/details/80691454
package com.panda.core.db.asyncdb;

import com.panda.core.db.impl.MongoDBService;
import com.panda.core.db.model.IEntity;
import org.mongodb.morphia.dao.DAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 异步存储数据
 * Created by Lovell on 9/26/16.
 */

public class DBThread implements Runnable {
    private static Logger logger = LoggerFactory.getLogger(DBThread.class);

    private DBQueue queue;

    public DBThread(DBQueue queue) {
        this.queue = queue;
    }
    @SuppressWarnings("uncheck")
    @Override
    public void run() {
        while(true) {
            try {
                int queueSize = queue.size();
                if (queueSize == 0) {
                    waitThead();
                } else {
                    IEntity entity = queue.pop();
                    if (entity == null) continue;

                    DAO dao = MongoDBService.getInstance().getDao(entity.getClass());
                    dao.save(entity);
                    if(queueSize>1000){
                        logger.warn("db queue size is then 1000,queueSize={}",queueSize);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    /**
     * 等待线程
     */
    private void waitThead() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
    }
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页