java游戏服务器架构中,请多多指教——manREDoo
定义接口
/**
* 游戏基础服务
*
* @author : 钟满红
*/
public interface IService {
/**
* 服务启动
*
* @throws Exception 异常
*/
public void startup() throws Exception;
/**
* 服务结束
*
* @throws Exception 异常
*/
public void shutdown() throws Exception;
}
服务管理
/**
* 游戏基础服务容器
* @author : 钟满红
*/
public final class Services implements IService {
private static final Map<Class<?>, IService> CACHE_SERVICE = new HashMap<>();
/**
* 基础服务对象注入
*/
private static <T extends IService> T valueOf(T t) {
CACHE_SERVICE.put(t.getClass(), t);
return t;
}
public static Collection<IService> getAll() {
return CACHE_SERVICE.values();
}
@Override
public void startup() throws Exception {
for (IService service : getAll()) {
try {
service.startup();
} catch (Exception e) {
}
}
}
@Override
public void shutdown() throws Exception {
for (IService service : getAll()) {
try {
service.shutdown();
} catch (Exception e) {
}
}
}
}
服务启动
/**
* <p>
* 游戏启动服务
* </p>
*
* @author : 钟满红
*/
public class GameApp {
private static final Log log = Logs.gameLog;
public static void main(String[] args) throws Exception {
Services services = new Services();
services.startup();
Thread shutdownHook = new Thread(() -> {
try {
services.shutdown();
} catch (Exception e) {
}
});
shutdownHook.setDaemon(true);
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
}