|
@@ -0,0 +1,77 @@
|
|
|
+package com.incubator.game.player;
|
|
|
+
|
|
|
+import com.incubator.game.GGame;
|
|
|
+import com.incubator.game.data.entity.PlayerInfoPO;
|
|
|
+
|
|
|
+import java.util.Queue;
|
|
|
+import java.util.concurrent.ConcurrentLinkedQueue;
|
|
|
+import java.util.concurrent.Executors;
|
|
|
+import java.util.concurrent.ScheduledExecutorService;
|
|
|
+import java.util.concurrent.TimeUnit;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 玩家对象池
|
|
|
+ */
|
|
|
+public final class PlayerPool {
|
|
|
+
|
|
|
+ private final Queue<Player> playerPool;
|
|
|
+ private final ScheduledExecutorService cleaner;
|
|
|
+
|
|
|
+ public PlayerPool() {
|
|
|
+ this.playerPool = new ConcurrentLinkedQueue<>();
|
|
|
+ this.cleaner = Executors.newSingleThreadScheduledExecutor();
|
|
|
+ // 定期清理空闲玩家
|
|
|
+ this.cleaner.scheduleAtFixedRate(this::cleanIdlePlayers, 10, 30, TimeUnit.SECONDS);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 获取玩家对象
|
|
|
+ */
|
|
|
+ public Player acquirePlayer(PlayerInfoPO playerInfoPO) {
|
|
|
+ Player player = this.playerPool.poll();
|
|
|
+ if (player == null) {
|
|
|
+ player = new Player(playerInfoPO);
|
|
|
+ }
|
|
|
+ player.data = playerInfoPO;
|
|
|
+ return player;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 玩家下线,归还玩家对象
|
|
|
+ */
|
|
|
+ public void releasePlayer(Player player) {
|
|
|
+ if (player != null) {
|
|
|
+ // 重置玩家状态
|
|
|
+ player.reset();
|
|
|
+ // 放回池中
|
|
|
+ this.playerPool.offer(player);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 定期清理空闲玩家
|
|
|
+ */
|
|
|
+ private void cleanIdlePlayers() {
|
|
|
+ while (this.playerPool.size() > GGame.maxIdlePlayers) {
|
|
|
+ Player player = this.playerPool.poll();
|
|
|
+ if (player != null) {
|
|
|
+ // 销毁玩家,释放资源
|
|
|
+ player.destroy();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 关闭对象池
|
|
|
+ */
|
|
|
+ public void shutdown() {
|
|
|
+ this.cleaner.shutdownNow();
|
|
|
+ this.playerPool.forEach(Player::destroy);
|
|
|
+ this.playerPool.clear();
|
|
|
+ }
|
|
|
+
|
|
|
+ public int getAvailablePlayers() {
|
|
|
+ return this.playerPool.size();
|
|
|
+ }
|
|
|
+
|
|
|
+}
|