线程管理模型

back_recharge
mashiyu 2019-01-08 18:46:36 +08:00
parent 32155b1435
commit 176ff89acf
7 changed files with 808 additions and 24 deletions

View File

@ -1,5 +1,6 @@
package com.ljsd;
import com.ljsd.jieling.db.redis.RedisUtil;
import com.ljsd.jieling.handler.BaseHandler;
import com.ljsd.jieling.logic.STableManager;
import com.ljsd.jieling.netty.server.NettyGameServer;
@ -7,6 +8,7 @@ import com.ljsd.jieling.network.NettyProperties;
import com.ljsd.jieling.network.NettyServerAutoConfiguration;
import com.ljsd.jieling.network.server.ProtocolsManager;
import com.ljsd.jieling.network.session.ISessionFactory;
import com.ljsd.jieling.thread.ThreadManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
@ -32,7 +34,6 @@ public class GameApplication {
private static NettyGameServer nettyServer = null;
public static int serverId = 0;
// public static ServerProperties serverProperties;
public static String coreIp;
public static boolean start = false;
public static void main(String[] args) throws Exception {
@ -53,7 +54,14 @@ public class GameApplication {
for (BaseHandler handler : gameHanderMap.values()) {
protocolsManager.addHandler(handler);
}
RedisUtil.getInstence().init(configurableApplicationContext);
STableManager.initialize("com.ljsd.jieling.config");
ThreadManager threadManager = new ThreadManager();
threadManager.init(configurableApplicationContext);
final NettyServerAutoConfiguration netServerConfig = configurableApplicationContext.getBean(NettyServerAutoConfiguration.class);
NettyProperties properties = netServerConfig.getNettyProperties();
try {

View File

@ -0,0 +1,654 @@
package com.ljsd.jieling.db.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class RedisUtil {
private RedisUtil() {
}
public static RedisUtil getInstence() {
return InnerClass.instance;
}
private static class InnerClass {
private static final RedisUtil instance = new RedisUtil();
}
@Autowired
private StringRedisTemplate redisTemplate;
public void init(ConfigurableApplicationContext configurableApplicationContext){
redisTemplate = configurableApplicationContext.getBean(StringRedisTemplate.class);
}
/**
*
*
* @param key
*
* @param time
* ()
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* key
*
* @param key
* null
* @return () 0
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* key
*
* @param key
*
* @return true false
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
*
* @param key
*
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
*
*
* @param key
*
* @return
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
*
*
* @param key
*
* @param value
*
* @return true false
*/
public boolean set(String key, String value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
*
* @param key
*
* @param value
*
* @param time
* () time0 time0
* @return true false
*/
public boolean set(String key, String value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
*
* @param key
*
* @param delta
* (0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
*
*
* @param key
*
* @param delta
* (0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
*
* @param key
* null
* @param item
* null
* @return
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* hashKey
*
* @param key
*
* @return
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key
*
* @param map
*
* @return true false
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet
*
* @param key
*
* @param map
*
* @param time
* ()
* @return true false
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* hash,
*
* @param key
*
* @param item
*
* @param value
*
* @return true false
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* hash,
*
* @param key
*
* @param item
*
* @param value
*
* @param time
* () :hash,
* @return true false
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* hash
*
* @param key
* null
* @param item
* 使 null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* hash
*
* @param key
* null
* @param item
* null
* @return true false
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash ,
*
* @param key
*
* @param item
*
* @param by
* (0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash
*
* @param key
*
* @param item
*
* @param by
* (0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* keySet
*
* @param key
*
* @return
*/
public Set<String> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* valueset,
*
* @param key
*
* @param value
*
* @return true false
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* set
*
* @param key
*
* @param values
*
* @return
*/
public long sSet(String key, String... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* set
*
* @param key
*
* @param time
* ()
* @param values
*
* @return
*/
public long sSetAndTime(String key, long time, String... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* set
*
* @param key
*
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* value
*
* @param key
*
* @param values
*
* @return
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
* list
*
* @param key
*
* @param start
*
* @param end
* 0 -1
* @return
*/
public List<String> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* list
*
* @param key
*
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* list
*
* @param key
*
* @param index
* index>=0 0 1 index<0-1-2
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* list
*
* @param key
*
* @param value
*
* @return
*/
public boolean lSet(String key, String value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* list
*
* @param key
*
* @param value
*
* @param time
* ()
* @return
*/
public boolean lSet(String key, String value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* list
*
* @param key
*
* @param value
*
* @return
*/
public boolean lSet(String key, List<String> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* list
*
* @param key
*
* @param value
*
* @param time
* ()
* @return
*/
public boolean lSet(String key, List<String> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* list
*
* @param key
*
* @param index
*
* @param value
*
* @return
*/
public boolean lUpdateIndex(String key, long index, String value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Nvalue
*
* @param key
*
* @param count
*
* @param value
*
* @return
*/
public long lRemove(String key, long count, String value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}

View File

@ -196,29 +196,21 @@ public class ProtocolsManager implements ProtocolsAbstract {
}
final ISession session = (ISession) gameSession;
PacketNetData packetNetData = new PacketNetData((byte[])obj);
session.setUid(packetNetData.getUserId());
session.setToken(packetNetData.getToken());
if (packetNetData.getMsgId()==1000){
new Thread(new Runnable() {
@Override
public void run() {
Random random = new Random();
int time = random.nextInt(6)+1;
try {
System.out.println("sleep time : "+time);
Thread.sleep(time*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.currentThread().setName("OOOOOOOOO");
MessageUtil.sendHeartBeat(session);
}
}).start();
dealHeartBeat(session);
return;
}
int resultCode = checkAndRefresh(session,packetNetData);
if (resultCode != 0 ){
MessageUtil.sendErrorCode(session);
return;
}
BaseHandler baseHandler = handlers.get(packetNetData.getMsgId());
if (baseHandler == null) {
LOGGER.info("request unknow commond : " + packetNetData.getMsgId());
@ -232,8 +224,44 @@ public class ProtocolsManager implements ProtocolsAbstract {
}
}
private void dealHeartBeat(ISession session) {
new Thread(new Runnable() {
@Override
public void run() {
Random random = new Random();
int time = random.nextInt(6)+1;
try {
System.out.println("sleep time : "+time);
Thread.sleep(time*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.currentThread().setName("OOOOOOOOO");
MessageUtil.sendHeartBeat(session);
}
}).start();
// MessageUtil.sendHeartBeat(session);
}
private int checkAndRefresh(ISession session, PacketNetData packetNetData) {
int myToken = 0;
if (packetNetData.getMsgId()== MessageTypeProto.MessageType.LOGIN_REQUEST_VALUE){
}else if (packetNetData.getMsgId()== MessageTypeProto.MessageType.LOGIN_REQUEST_VALUE){
}else {
}
if (myToken != packetNetData.getToken()){
return 1;
}
session.setUserLoginTime(System.currentTimeMillis()/1000);
session.setToken(myToken);
return 0;
}
@Override

View File

@ -0,0 +1,66 @@
package com.ljsd.jieling.thread;
import com.ljsd.jieling.thread.task.TestTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadManager {
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadManager.class);
private TestTask testTask;
private ScheduledThreadPoolExecutor scheduledExecutor; //管理task
public void init(ConfigurableApplicationContext configurableApplicationContext) {
testTask = configurableApplicationContext.getBean(TestTask.class);
go();
}
static class ScheduleThreadFactory implements ThreadFactory {
final ThreadGroup group;
final AtomicInteger threadNumber = new AtomicInteger(1);
final String namePrefix;
ScheduleThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
namePrefix = "ScheduleThreadPool" + "-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
public void go() {
scheduledExecutor = new ScheduledThreadPoolExecutor(8, new ScheduleThreadFactory());
// testTask 已秒为单位 延迟10s, 间隔30s为周期执行
scheduledExecutor.scheduleAtFixedRate(testTask, 10, 30, TimeUnit.SECONDS);
LOGGER.info("All Task running ...");
}
}

View File

@ -0,0 +1,24 @@
package com.ljsd.jieling.thread.task;
import com.ljsd.jieling.db.redis.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class TestTask implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(TestTask.class);
@Override
public void run() {
doLogic();
}
private void doLogic() {
long str = RedisUtil.getInstence().incr("TestTask",1L);
LOGGER.info("--> RedisUtil.incr : str = "+str);
LOGGER.info("TestTask ... ");
}
}

View File

@ -38,9 +38,7 @@ public class MessageUtil {
if (backMessage.length != 0) {
System.arraycopy(backMessage, 0, bytes, pos, backMessage.length);
}
int[] secretKey = Tea.KEY;
return Tea.encrypt2(bytes, secretKey);
}
@ -69,6 +67,11 @@ public class MessageUtil {
session.writeAndFlush(byteBuf);
}
public static void sendErrorCode(ISession session) {
}
// public static void sendErrorResponse(Msg msg, GeneratedMessage error_message, int msgId) throws Exception {
// String protoEntity = Base64.getEncoder().encodeToString(error_message.toByteArray());
// BaseGlobal.redisApp.hset(RedisKey.RESPONSE, String.valueOf(msg.getUid()), String.valueOf(Math.abs(msg.getIndex())), new ProtoEntity(msgId, protoEntity), -1);

View File

@ -1,5 +1,6 @@
#server info
server.id = 10180
server.openTime = 20190101000101
# redis config
@ -34,7 +35,7 @@ mongodb.options.connectTimeout = 1000
mongodb.options.socketTimeout = 0
mongodb.options.threadsAllowedToBlockForConnectionMultiplier = 20
mongodb.options.connectionsPerHost = 256
mongodb.options.minConnectionsPerHost = 100
mongodb.options.minConnectionsPerHost = 5
mongodb.options.maxConnectionIdleTime = 1000