Browse Source

游戏计分

master
zhizhi wu 5 years ago
parent
commit
1cb2576515
  1. 2
      game/src/main/java/com/ccsens/game/bean/dto/message/GameMessageCountOut.java
  2. 55
      game/src/main/java/com/ccsens/game/netty/wsserver/WebSocketHandler.java
  3. 94
      game/src/main/java/com/ccsens/game/service/ClientService.java
  4. 15
      game/src/main/java/com/ccsens/game/service/ScreenService.java
  5. 4
      game/src/main/resources/application.yml

2
game/src/main/java/com/ccsens/game/bean/dto/message/GameMessageCountOut.java

@ -13,7 +13,7 @@ public class GameMessageCountOut extends BaseMessageDto {
private int totalScore; private int totalScore;
} }
private Data data; private Data data = new Data();
public GameMessageCountOut(){ public GameMessageCountOut(){
setType(WebConstant.Message_Type.Count.phase); setType(WebConstant.Message_Type.Count.phase);

55
game/src/main/java/com/ccsens/game/netty/wsserver/WebSocketHandler.java

@ -1,10 +1,16 @@
package com.ccsens.game.netty.wsserver; package com.ccsens.game.netty.wsserver;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ccsens.game.bean.dto.ClientDto;
import com.ccsens.game.bean.dto.message.*; import com.ccsens.game.bean.dto.message.*;
import com.ccsens.game.netty.ChannelManager; import com.ccsens.game.netty.ChannelManager;
import com.ccsens.game.service.IClientService; import com.ccsens.game.service.IClientService;
import com.ccsens.game.service.IMessageService; import com.ccsens.game.service.IMessageService;
import com.ccsens.game.util.GameConstant;
import com.ccsens.util.RedisUtil;
import com.ccsens.util.WebConstant; import com.ccsens.util.WebConstant;
import com.ccsens.util.bean.message.common.MessageConstant; import com.ccsens.util.bean.message.common.MessageConstant;
import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler;
@ -16,8 +22,12 @@ import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.Set;
/** /**
* @author wei * @author wei
*/ */
@ -33,6 +43,8 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<BaseMessageDto
private IClientService clientService; private IClientService clientService;
@Autowired @Autowired
private IMessageService messageService; private IMessageService messageService;
@Autowired
private RedisUtil redisUtil;
@Override @Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception { public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
@ -76,7 +88,7 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<BaseMessageDto
@Override @Override
protected void channelRead0(ChannelHandlerContext ctx, BaseMessageDto baseMessage) throws Exception { protected void channelRead0(ChannelHandlerContext ctx, BaseMessageDto baseMessage) throws Exception {
log.info("接受到消息的时间+++++++++++++++++++++++:{}",System.currentTimeMillis()); log.info("接受到消息的时间+++++++++++++++++++++++{}{},{}",baseMessage.getType(), new Date(), System.currentTimeMillis());
MessageConstant.GameClientMessageType gameClientMessageType = MessageConstant.GameClientMessageType.valueOf(baseMessage.getType()); MessageConstant.GameClientMessageType gameClientMessageType = MessageConstant.GameClientMessageType.valueOf(baseMessage.getType());
System.out.println(baseMessage); System.out.println(baseMessage);
@ -109,8 +121,11 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<BaseMessageDto
String userId = ChannelManager.getUserIdByChannel(ctx.channel()); String userId = ChannelManager.getUserIdByChannel(ctx.channel());
String recordId = ChannelManager.getRecordIdByChannel(ctx.channel()); String recordId = ChannelManager.getRecordIdByChannel(ctx.channel());
log.info("统计分数:{},{}",userId, recordId); log.info("统计分数:{},{}",userId, recordId);
GameMessageCountOut gameMessageCountOut = clientService.clientAddTimes(userId,recordId); long t1 = System.currentTimeMillis();
log.info("统计分数返回结果:{}", gameMessageCountOut); // GameMessageCountOut gameMessageCountOut = clientService.clientAddTimes(userId,recordId);
GameMessageCountOut gameMessageCountOut = clientAddTimes(userId,recordId);
long t2 = System.currentTimeMillis();
log.info("统计分数返回结果:{}, 计算耗时:{}", gameMessageCountOut, t2 - t1);
ChannelManager.sendTo(ctx.channel(), gameMessageCountOut); ChannelManager.sendTo(ctx.channel(), gameMessageCountOut);
Long sendTime = System.currentTimeMillis(); Long sendTime = System.currentTimeMillis();
log.info("消耗的时长:{}", sendTime - receiveTime); log.info("消耗的时长:{}", sendTime - receiveTime);
@ -131,6 +146,40 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<BaseMessageDto
} }
} }
public GameMessageCountOut clientAddTimes(String userId, String recordId) {
GameMessageCountOut gameMessageCountOut = new GameMessageCountOut();
log.info("userId:{}", userId);
if (StrUtil.isBlank(userId) || StrUtil.isBlank(userId)) {
return gameMessageCountOut;
}
Long recordIdLong = Long.parseLong(recordId);
String gameUserKey = GameConstant.generateGameKey(recordIdLong);
Set<ZSetOperations.TypedTuple<Object>> typedTuples = redisUtil.zsRevGetWithScore(gameUserKey, 0, -1);
if (CollectionUtil.isEmpty(typedTuples)) {
return gameMessageCountOut;
}
for(ZSetOperations.TypedTuple<Object> type : typedTuples) {
ClientDto.RedisUser user = JSON.parseObject((String)type.getValue(), ClientDto.RedisUser.class);
if (user.getUserId().longValue() == Long.parseLong(userId)) {
int score = type.getScore().intValue();
String userStatus = GameConstant.generateGameStatusKey(recordIdLong);
String gameStausObj = (String)redisUtil.get(userStatus);
if (StrUtil.isBlank(gameStausObj) || gameStausObj.equals(String.valueOf(GameConstant.GAME_COMPLETED))){
gameMessageCountOut = new GameMessageCountOut(score/100, score);
return gameMessageCountOut;
}
score += 100;
redisUtil.zsSet(gameUserKey, JSON.toJSONString(user), score);
gameMessageCountOut.getData().setTotalScore(score);
gameMessageCountOut.getData().setTotalTimes(score/100);
return gameMessageCountOut;
}
};
return gameMessageCountOut;
}
private void doAuthMessage(ChannelHandlerContext ctx, AuthMessageDto message) throws Exception { private void doAuthMessage(ChannelHandlerContext ctx, AuthMessageDto message) throws Exception {
WebConstant.Message_Auth_Event event = WebConstant.Message_Auth_Event.phaseOf(message.getEvent()); WebConstant.Message_Auth_Event event = WebConstant.Message_Auth_Event.phaseOf(message.getEvent());
switch (event) { switch (event) {

94
game/src/main/java/com/ccsens/game/service/ClientService.java

@ -358,26 +358,86 @@ public class ClientService implements IClientService {
*/ */
@Override @Override
public GameMessageCountOut clientAddTimes(String userId, String recordId) { public GameMessageCountOut clientAddTimes(String userId, String recordId) {
long t1 = System.currentTimeMillis();
GameMessageCountOut gameMessageCountOut = new GameMessageCountOut(); GameMessageCountOut gameMessageCountOut = new GameMessageCountOut();
long t2 = System.currentTimeMillis();
log.info("创建out耗时:{}", t2 - t1);
log.info("userId:{}", userId); log.info("userId:{}", userId);
if (ObjectUtil.isNotNull(userId)) { if (StrUtil.isBlank(userId) || StrUtil.isBlank(userId)) {
GameUserJoinExample gameUserJoinExample = new GameUserJoinExample(); return gameMessageCountOut;
gameUserJoinExample.createCriteria().andUserIdEqualTo(Long.valueOf(userId)).andRecordIdEqualTo(Long.valueOf(recordId)); }
List<GameUserJoin> userJoinList = gameUserJoinDao.selectByExample(gameUserJoinExample); long t8 = System.currentTimeMillis();
log.info("游戏对象:{}", userJoinList); log.info("判断耗时:{}", t8-t1);
if (CollectionUtil.isNotEmpty(userJoinList)) { Long recordIdLong = Long.parseLong(recordId);
GameUserJoin userJoin = userJoinList.get(0); String gameUserKey = GameConstant.generateGameKey(recordIdLong);
userJoin.setTimes(userJoin.getTimes() + 1); long t3 = System.currentTimeMillis();
userJoin.setScore(userJoin.getScore() + 100); log.info("生成key耗时:{}", t3-t2);
log.info("更新分数:{}", userJoin); Set<ZSetOperations.TypedTuple<Object>> typedTuples = redisUtil.zsRevGetWithScore(gameUserKey, 0, -1);
gameUserJoinDao.updateByPrimaryKeySelective(userJoin); long t4 = System.currentTimeMillis();
//更新redis log.info("查询分数耗时:{}", t4-t3);
ClientDto.RedisUser user = ClientDto.RedisUser.getInstance(userJoin);
log.info("游戏id:{}, 对象:{}, 分数:{}", recordId, user, userJoin.getScore()); if (CollectionUtil.isEmpty(typedTuples)) {
redisUtil.zsSet(GameConstant.generateGameKey(Long.parseLong(recordId)), JSON.toJSONString(user), userJoin.getScore(), GameConstant.REDIS_TIME); return gameMessageCountOut;
gameMessageCountOut = new GameMessageCountOut(userJoin.getTimes(), userJoin.getScore());
}
} }
long t5 = System.currentTimeMillis();
log.info("判断分数是否为空耗时:{}", t5-t4);
log.info("查询耗时:{}", t5 - t8);
for(ZSetOperations.TypedTuple<Object> type : typedTuples) {
long a1 = System.currentTimeMillis();
ClientDto.RedisUser user = JSON.parseObject((String)type.getValue(), ClientDto.RedisUser.class);
long a2 = System.currentTimeMillis();
log.info("json转换耗时:{}", a2-a1);
if (user.getUserId().longValue() == Long.parseLong(userId)) {
int score = type.getScore().intValue();
long a3 = System.currentTimeMillis();
log.info("获取分数耗时:{}", a3-a2);
String userStatus = GameConstant.generateGameStatusKey(recordIdLong);
long a4 = System.currentTimeMillis();
log.info("生成游戏状态key耗时:{}", a4-a3);
String gameStausObj = (String)redisUtil.get(userStatus);
long a5 = System.currentTimeMillis();
log.info("获取状态耗时:{}", a5-a4);
log.info("gameStatus:{},equals:{}",gameStausObj, gameStausObj.equals(String.valueOf(GameConstant.GAME_COMPLETED)));
if (StrUtil.isBlank(gameStausObj) || gameStausObj.equals(String.valueOf(GameConstant.GAME_COMPLETED))){
gameMessageCountOut = new GameMessageCountOut(score/100, score);
return gameMessageCountOut;
}
long a6 = System.currentTimeMillis();
log.info("判断游戏结束耗时:{}", a6-a5);
score += 100;
redisUtil.zsSet(gameUserKey, JSON.toJSONString(user), score);
long a7 = System.currentTimeMillis();
log.info("更新redis耗时:{}", a7-a6);
gameMessageCountOut.getData().setTotalScore(score);
gameMessageCountOut.getData().setTotalTimes(score/100);
long t = System.currentTimeMillis();
log.info("循环耗时:{}", t - t5);
log.info("返回耗时:{},循环耗时:{}", t-a7, t-t5);
return gameMessageCountOut;
}
};
long t = System.currentTimeMillis();
log.info("总耗时:{}", t- t1);
// if (ObjectUtil.isNotNull(userId)) {
// GameUserJoinExample gameUserJoinExample = new GameUserJoinExample();
// gameUserJoinExample.createCriteria().andUserIdEqualTo(Long.valueOf(userId)).andRecordIdEqualTo(Long.valueOf(recordId));
// List<GameUserJoin> userJoinList = gameUserJoinDao.selectByExample(gameUserJoinExample);
// log.info("游戏对象:{}", userJoinList);
// if (CollectionUtil.isNotEmpty(userJoinList)) {
// GameUserJoin userJoin = userJoinList.get(0);
// userJoin.setTimes(userJoin.getTimes() + 1);
// userJoin.setScore(userJoin.getScore() + 100);
// log.info("更新分数:{}", userJoin);
// gameUserJoinDao.updateByPrimaryKeySelective(userJoin);
// //更新redis
// ClientDto.RedisUser user = ClientDto.RedisUser.getInstance(userJoin);
// log.info("游戏id:{}, 对象:{}, 分数:{}", recordId, user, userJoin.getScore());
// redisUtil.zsSet(GameConstant.generateGameKey(Long.parseLong(recordId)), JSON.toJSONString(user), userJoin.getScore(), GameConstant.REDIS_TIME);
// gameMessageCountOut = new GameMessageCountOut(userJoin.getTimes(), userJoin.getScore());
// }
// }
return gameMessageCountOut; return gameMessageCountOut;
} }
} }

15
game/src/main/java/com/ccsens/game/service/ScreenService.java

@ -748,6 +748,21 @@ public class ScreenService implements IScreenService{
gameRecord.setGameStatus(GameConstant.GAME_COMPLETED); gameRecord.setGameStatus(GameConstant.GAME_COMPLETED);
gameRecordDao.updateByPrimaryKeySelective(gameRecord); gameRecordDao.updateByPrimaryKeySelective(gameRecord);
redisUtil.set(GameConstant.generateGameStatusKey(gameRecord.getId()), JSON.toJSONString(gameRecord), GameConstant.REDIS_TIME); redisUtil.set(GameConstant.generateGameStatusKey(gameRecord.getId()), JSON.toJSONString(gameRecord), GameConstant.REDIS_TIME);
//TODO 将redis里的分数同步到数据库
String key = GameConstant.generateGameKey(start.getMemberRecord());
Set<ZSetOperations.TypedTuple<Object>> typedTuples = redisUtil.zsGetWithScore(key, 0, -1);
if (CollectionUtil.isNotEmpty(typedTuples)) {
typedTuples.forEach(type -> {
int score = type.getScore().intValue();
ClientDto.RedisUser user = JSON.parseObject((String) type.getValue(), ClientDto.RedisUser.class);
GameUserJoin join = new GameUserJoin();
join.setId(user.getId());
join.setScore(score);
join.setTimes(score/100);
gameUserJoinDao.updateByPrimaryKeySelective(join);
});
}
}); });
//更新用户游戏开始时间和结束时间 //更新用户游戏开始时间和结束时间
gameUserJoinDao.updateTimeBatch(gameRecord.getId(), gameRecord.getStartTime(), gameRecord.getEndTime()); gameUserJoinDao.updateTimeBatch(gameRecord.getId(), gameRecord.getStartTime(), gameRecord.getEndTime());

4
game/src/main/resources/application.yml

@ -1,4 +1,4 @@
spring: spring:
profiles: profiles:
active: dev active: test
include: common, util-dev include: common, util-test
Loading…
Cancel
Save