该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
用户数据异步持久化
当玩家的数据发生变动时,我们需要将最新的数据保存到数据库。这里有一个问题,当玩家数据有部分变动的时候,我们不可能即使保存到数据库的,这样对数据库的压力太大。所以,我们需要有独立线程来完成数据的异步保存。这里又要搬出我们可爱的生产者消费者模型啦。
[java] view plain copy
/**
* 用户数据异步持久化的服务
* @author kingston
*/
public class DbService {
private static volatile DbService instance;
public static DbService getInstance() {
if (instance == null) {
synchronized (DbService.class) {
if (instance == null) {
instance = new DbService();
}
}
}
return instance;
}
/**
* 启动消费者线程
*/
public void init() {
new Thread(new Worker()).start();
}
@SuppressWarnings("rawtypes")
private BlockingQueue queue = new BlockingUniqueQueue<>();
private final AtomicBoolean run = new AtomicBoolean(true);
public void add2Queue(BaseEntity> entity) {
this.queue.add(entity);
}
private class Worker implements Runnable {
@Override
public void run() {
while(run.get()) {
try {
BaseEntity> entity = queue.take();
saveToDb(entity);
} catch (InterruptedException e) {
LoggerUtils.error("", e);
}
}
}
}
/**
* 数据真正持久化
* @param entity
*/
private void saveToDb(BaseEntity> entity) {
entity.save();
}
}
到这里,关于配置数据库和用户数据库的概念及实现就介绍完毕了