一个小工具合服

package dao

package com.game2sky.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.game2sky.domain.BaseActivity;

public interface BenfuDao {

@Select("show tables")
List<String> selectTableNames();

@Select("SELECT COUNT(1) FROM ${tableName}")
int count(@Param("tableName") String tableName);

@Select("SELECT serverIds FROM ${tableName}")
List<String> getServerGroup(@Param("tableName") String tableName);

@Select("select playerId FROM inst_player WHERE isRobot= #{isRobot}")
List<Long> findRobotPlayerId(@Param("isRobot") int isRobot);

@Delete("delete FROM ${tableName} WHERE playerId= #{playerId}")
void deleteRobot(@Param("tableName") String tableName,@Param("playerId") long playerId);


@Delete("delete from inst_arena")
void deleteArena();

@Delete("delete from inst_player_arena")
void deletePlayerArena();

@Delete("delete from inst_server_config")
void deleteServerConfig();

@Delete("delete from inst_fight_record")
void deleteFightRecord();

@Delete("delete from inst_fight_replay")
void deleteFightReplay();

@Delete("delete from ${tableName}")
void deleteTable(@Param("tableName") String tableName);

@Insert("insert into inst_server_config set configKey = #{configKey}, configValue = #{configValue}, modifyTime = #{modifyTime}")
void insertServerConfigSwitch(@Param("configKey") String configKey, @Param("configValue") String configValue, @Param("modifyTime") long modifyTime);

@Select("select configValue from inst_server_config where configKey = #{configKey}")
List<String> findServerConfig(@Param("configKey") String configKey);

@Update("update inst_server_config set configValue = #{configValue} where configKey = #{configKey}")
void update(@Param("configValue") String configValue, @Param("configKey") String configKey);

@Select("select * FROM base_activity WHERE state != 5 and onOff = 1 and endTime > #{endTime}")
List<BaseActivity> findRunActivity(@Param("endTime") long endTime);

@Select("select ${fieldName} FROM ${tableName}")
List<Long> findFightId(@Param("fieldName") String fieldName,@Param("tableName") String table);

@Delete("<script>"
+ "delete from ${tableName} where ${fieldName} in "
+ "<foreach item='item' index='index' collection='list' open='(' separator=',' close=')'>"
+ "#{item}"
+ "</foreach>"
+ "</script>")
void deleteRepeatedId(@Param("tableName") String tableName,@Param("fieldName") String fieldName,@Param("list") List<Long> list);


@Select("<script>"
+ "select count(*) FROM base_activity WHERE baseActivityType in "
+ "<foreach item='id' collection='list' open='(' separator=',' close=')'>"
+ "#{id}"
+ "</foreach>"
+ "and endTime > #{currTime}"
+ "</script>")
int findQuanfuRankActivity(@Param("currTime") long currTime,@Param("list") List<Integer> list);

@Select("select playerId FROM ${tableName} WHERE playerId not in ( select playerId from inst_player )")
List<Long> selectOtherServerData(@Param("tableName") String tableName);

@Select("SELECT column_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE table_name='${tableName}' AND constraint_name='PRIMARY' limit 1")
String selectPriKey(@Param("tableName") String tableName);

@Update("CREATE TABLE If Not Exists ${tableName} ("
+"`playerId` bigint(20) NOT NULL,"
+"`mode` smallint(6) NOT NULL DEFAULT 0,"
+"`bestScore` int(11) DEFAULT NULL,`bestFloor` int(11) DEFAULT NULL,`times` smallint(6) DEFAULT NULL,`score` int(11) DEFAULT NULL,`startTime` bigint(20) DEFAULT NULL,`bestUpdateTime` bigint(20) DEFAULT NULL,"
+"`histoFloor` int(11) DEFAULT NULL,`modeSelectState` smallint(2) DEFAULT NULL,`preStartTime` bigint(20) DEFAULT NULL,`preRankFloor` int(11) DEFAULT NULL,`preRankScore` int(11) DEFAULT NULL,`preRankRange` int(11) DEFAULT NULL,"
+"`serverId` int(11) DEFAULT NULL,`leftTime` int(11) DEFAULT NULL,`preLeftTime` int(11) DEFAULT NULL,`preSendReward` tinyint(2) NOT NULL,`preMode` smallint(6) DEFAULT NULL,`preRangeRewardTime` bigint(20) DEFAULT NULL,"
+"`firstFloor` int(11) DEFAULT NULL,`jumpInfo` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,`modifyVersion` bigint(19) DEFAULT NULL,`heroKey` int(11) DEFAULT NULL,"
+"`guid` bigint(20) NOT NULL,`bestHeroId` int(11) DEFAULT NULL,`preBestHeroId` int(11) DEFAULT NULL,`preBestUpdateTime` bigint(20) DEFAULT NULL,`bestHeroLv` int(11) DEFAULT 0,`preBestHeroLv` int(11) DEFAULT 0,"
+"PRIMARY KEY (`guid`) USING BTREE,INDEX `playerId`(`playerId`) USING BTREE) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact")
void createTable(@Param("tableName") String tableName);
}

 

##############3###################

package com.game2sky.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.game2sky.domain.ProcessDBSConfig;


public interface ProcessDBSConfigDao {

@Select("select * from ProcessDBSConfig")
List<ProcessDBSConfig> loadAll();

@Select("select * from ProcessDBSConfig where inIp = #{inIp} and port = #{port}")
List<ProcessDBSConfig> findByInIpAndPort(@Param("inIp") String inIp, @Param("port") int port);

@Delete("delete FROM ProcessDBSConfig WHERE serverIds LIKE #{serverIds}")
void delete(@Param("serverIds") int serverIds);

@Update(value = "update ProcessDBSConfig set serverIds = #{serverIds} where id = #{id}")
void update(@Param("serverIds") String serverIds, @Param("id") int id);

}

 

*********************************************************************

 

deal package

package com.game2sky.deal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.ibatis.session.SqlSession;

import com.game2sky.Config;
import com.game2sky.dao.BenfuDao;
import com.game2sky.dao.ProcessBenfuConfigDao;
import com.game2sky.domain.BaseActivity;
import com.game2sky.util.UtilLog;
import com.game2sky.util.Utils;

/**
* 删除本服活动和相关重复配置数据.
*
* @author machao
* @version v0.1 2019年1月9日 下午5:30:36 machao
*/
public class DealBenfuData {
public static List<String> benfuTables = new ArrayList<>();
public static List<String> creatTables = new ArrayList<>();
static {
List<String> fileContent = Utils.getFileContent("deleteTable.txt");
benfuTables = fileContent;
List<String> creatContent = Utils.getFileContent("creatTable.txt");
creatTables = creatContent;
}

public static void deleteBenfuData() {
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();

for (int i : entry.getKey()) {
// 删除被合服的活动配置表
for (String tableName : benfuTables) {
SqlSession sqlSession = Config.dbSessionMap.get(i);
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);
benfuDao.deleteTable(tableName);
sqlSession.commit();
}
}
}

public static void creatBenfuData(){
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
SqlSession sqlSession = Config.dbSessionMap.get(entry.getValue());
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);

for (int i : entry.getKey()) {
// 删除被合服的活动配置表
for (String tableName : creatTables) {
StringBuilder builder = new StringBuilder();
builder.append(tableName).append("_").append(i);
benfuDao.createTable(builder.toString());
sqlSession.commit();
}
}
}

public static void insertServerConfigSwitch() {
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();

SqlSession sqlSession = Config.dbSessionMap.get(entry.getValue());
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);

long time = System.currentTimeMillis();
List<String> logicMergeChangeName = benfuDao.findServerConfig("logicMergeChangeName");
if(logicMergeChangeName != null && logicMergeChangeName.size() > 0){
benfuDao.update("on", "logicMergeChangeName");
}else{
benfuDao.insertServerConfigSwitch("logicMergeChangeName", "on", time);
}

// List<String> logicMergeResetRank = benfuDao.findServerConfig("logicMergeResetRank");
// if(logicMergeResetRank != null && logicMergeResetRank.size() > 0){
// benfuDao.update("on", "logicMergeResetRank");
// }else{
// benfuDao.insertServerConfigSwitch("logicMergeResetRank", "on", time);
// }

sqlSession.commit();
}

/**
* 校验各个区服的活动
*
* @return
*/
public static boolean checkActivityBeforeLogicMerge() {
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();

SqlSession sqlSessionTarget = Config.dbSessionMap.get(entry.getValue());
BenfuDao benfuDaoTarget = sqlSessionTarget.getMapper(BenfuDao.class);

List<BaseActivity> activityTargetList = benfuDaoTarget.findRunActivity(System.currentTimeMillis());
Map<Long,BaseActivity> activityTarget = convertActivityMap(activityTargetList);
for (int i : entry.getKey()) {
SqlSession sqlSessionMerge = Config.dbSessionMap.get(i);
BenfuDao benfuDaoMerge = sqlSessionMerge.getMapper(BenfuDao.class);
List<BaseActivity> activityMerge = benfuDaoMerge.findRunActivity(System.currentTimeMillis());
if(!checkActivity(activityTarget,activityMerge))
{
UtilLog.LOG_ERROR.error(entry.getValue()+","+i+" 活动数据不一致");
return false;
}
}
return true;

}
/**
* 检测全服排行榜类型活动
*
* @return
*/
public static boolean checkQuanfuRankActivity() {
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
List<Integer> sids = new ArrayList<>();
sids.addAll(entry.getKey());
sids.add(entry.getValue());

for (int i : sids) {
SqlSession sqlSessionMerge = Config.dbSessionMap.get(i);
BenfuDao benfuDao = sqlSessionMerge.getMapper(BenfuDao.class);
int count = benfuDao.findQuanfuRankActivity(System.currentTimeMillis(),Utils.getRankActivityTypes());
if(count > 0)
{
UtilLog.COMMON_LOG.error(entry.getValue()+","+i+"服 全服排名活动开启 不能进行合服");
UtilLog.LOG_ERROR.error(entry.getValue()+","+i+"服 全服排名活动开启 不能进行合服");
return false;
}
}
return true;

}

/**
* 查看所有要合的服的grouptype是不是一样的
* @return
*/
public static boolean checkCenterSame() {
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
List<Integer> sids = new ArrayList<>();
sids.addAll(entry.getKey());
ProcessBenfuConfigDao configDao = Config.mainSqlSession.getMapper(ProcessBenfuConfigDao.class);
String groupTypeTarget = configDao.findByServerId(entry.getValue()).get(0).getGroupType();
for (int i : sids) {
if(!configDao.findByServerId(i).get(0).getGroupType().equals(groupTypeTarget)){
UtilLog.COMMON_LOG.error(entry.getValue()+","+i+"服 grouptype和目标服组不一致 不能进行合服");
UtilLog.LOG_ERROR.error(entry.getValue()+","+i+"服 grouptype和目标服组不一致 不能进行合服");
return false;
}
}
return true;

}


/**
* list to Map
*
*
* @param activityTarget
* @return
*/
public static Map<Long,BaseActivity> convertActivityMap(List<BaseActivity> activityTarget)
{
Map<Long,BaseActivity> result = new HashMap<Long,BaseActivity>();
for(BaseActivity config :activityTarget)
{
//不能有explore活动,否则需要等活动结束后合服
// if(config.getActivityType() == 10061){
// UtilLog.LOG_ERROR.error("不能进行逻辑合服,存在explore活动,需要等活动结束后合服");
// System.out.println("不能进行逻辑合服,存在explore活动,需要等活动结束后合服");
// UtilLog.COMMON_LOG.info("不能进行逻辑合服,存在explore活动,需要等活动结束后合服");
// System.exit(1);
// }
result.put(config.getBaseActivityId(), config);
}
return result;
}
/**
* 具体校验活动内容
*
* @param activityTarget
* @param activityMerge
* @return
*/
public static boolean checkActivity( Map<Long,BaseActivity> activityTarget,List<BaseActivity> activityMerge)
{
//判断运营的活动 是否数量一致
if(activityTarget.size() != activityMerge.size())
{
UtilLog.LOG_ERROR.error("活动数量不一致");
return false;
}
//分析具体的是否一致
for(BaseActivity config :activityMerge)
{
BaseActivity target = activityTarget.get(config.getBaseActivityId());
if(target == null)
{
UtilLog.LOG_ERROR.error("活动数据不一致 ActivityConfig null activityId = "+config.getBaseActivityId());
return false;
}
if(!checkActivityConfig(target,config))
{
UtilLog.LOG_ERROR.error("活动数量不一致 ActivityConfig Data not equals activityId = "+config.getBaseActivityId());
return false;
}
}
return true;
}

public static boolean checkActivityConfig(BaseActivity trget,BaseActivity merge)
{
if(!trget.getBaseActivityId().equals(merge.getBaseActivityId()))
{
UtilLog.LOG_ERROR.error("getActivityId not equals target ="+trget.getBaseActivityId()+"merger = "+ merge.getBaseActivityId());
return false;
}
if(!trget.getStartTime().equals(merge.getStartTime()))
{
UtilLog.LOG_ERROR.error("getStartTime not equals target ="+trget.getStartTime()+"merger = "+ merge.getStartTime());
return false;
}
if(!trget.getEndTime().equals(merge.getEndTime()))
{
UtilLog.LOG_ERROR.error("getEndTime not equals target ="+trget.getEndTime()+"merger = "+ merge.getEndTime());
return false;
}
if(!trget.getRewardTime().equals(merge.getRewardTime()))
{
UtilLog.LOG_ERROR.error("getRewardTime not equals target ="+trget.getRewardTime()+"merger = "+ merge.getRewardTime());
return false;
}
if(trget.getOnOff() != merge.getOnOff())
{
UtilLog.LOG_ERROR.error("getOnOff not equals target ="+trget.getOnOff()+"merger = "+ merge.getOnOff());
return false;
}
if(trget.getState() != merge.getState())
{
UtilLog.LOG_ERROR.error("getState not equals target ="+trget.getState()+"merger = "+ merge.getState());
return false;
}
if(!trget.getEffectStartTime().equals(merge.getEffectStartTime()))
{
UtilLog.LOG_ERROR.error("getEffectStartTime not equals target ="+trget.getEffectStartTime()+"merger = "+ merge.getEffectStartTime());
return false;
}
if(!trget.getEffectEndTime().equals(merge.getEffectEndTime()))
{
UtilLog.LOG_ERROR.error("getEffectEndTime not equals target ="+trget.getEffectEndTime()+"merger = "+ merge.getEffectEndTime());
return false;
}
if(trget.getIsShow() != merge.getIsShow())
{
UtilLog.LOG_ERROR.error("getIsShow not equals target ="+trget.getIsShow()+"merger = "+ merge.getIsShow());
return false;
}
return true;
}

}

 

##############################5########################

package com.game2sky.deal;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import org.apache.ibatis.session.SqlSession;

import com.game2sky.Config;
import com.game2sky.dao.ConfigServerZoneDao;
import com.game2sky.dao.DataSourceConfigDao;
import com.game2sky.dao.DataSourceDictConfigDao;
import com.game2sky.dao.DataSourceRedisConfigDao;
import com.game2sky.dao.MainServerDao;
import com.game2sky.dao.ProcessBenfuConfigDao;
import com.game2sky.dao.ProcessDBSConfigDao;
import com.game2sky.domain.ConfigServerZone;
import com.game2sky.domain.DataSourceConfig;
import com.game2sky.util.SqlSessionFactoryUtil;
import com.game2sky.util.UtilLog;
import com.game2sky.util.Utils;

/**
* 更新主服zoneId和数据源信息.
*
* @author machao
* @version v0.1 2019年1月9日 下午5:30:36 machao
*/
public class DealMainServerData {

public static void checkUpdateOtherMainServerZone(){
//当前平台是安卓 新星大区
SqlSession mainSqlSession = null;
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
if(Config.platformId == 1){
if(entry.getValue() > 2000 && entry.getValue() < 3000){
// 创建主服数据库连接
mainSqlSession = SqlSessionFactoryUtil.openSession(Utils.getFilePath("mybatis-config-main-yh.xml"));
}
}else if(Config.platformId == 4){
//当前平台是ios 新世界大区
if(entry.getValue() > 6000 && entry.getValue() < 7000){
// 创建主服数据库连接
mainSqlSession = SqlSessionFactoryUtil.openSession(Utils.getFilePath("mybatis-config-main-gw.xml"));
}
}

if(mainSqlSession != null){
UtilLog.COMMON_LOG.info("...开始修改其他主服config配置...");
updateOtherMainZoneId(mainSqlSession);
UtilLog.COMMON_LOG.info("...完成修改其他主服config配置...");
}
}

public static void updateOtherMainZoneId(SqlSession sqlSession) {
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
int newZoneId = entry.getValue();

long openTime = Config.zoneMap.get(entry.getValue()).getOpenTime();

MainServerDao mainDao = sqlSession.getMapper(MainServerDao.class);

for (int i : entry.getKey()) {
List<Integer> sidsByZoneId = getSidsByZoneId(i);
for (int sid :sidsByZoneId) {
mainDao.updateZoneIdAndServerTime(newZoneId,openTime, sid);
UtilLog.COMMON_LOG.info("...updateOtherMainZoneId:"+sid);
}
}
sqlSession.commit();
}

public static List<Integer> getSidsByZoneId(int zoneId){
List<Integer> l = new ArrayList<>();
for (ConfigServerZone con : Config.zoneMap.values()) {
if(con.getZoneId() == zoneId){
l.add(con.getServerId());
}
}
return l;
}

public static void updateZoneId() {
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
int newZoneId = entry.getValue();

long openTime = Config.zoneMap.get(entry.getValue()).getOpenTime();

SqlSession sqlSession = Config.mainSqlSession;
MainServerDao mainDao = sqlSession.getMapper(MainServerDao.class);

for (int i : entry.getKey()) {
List<Integer> sidsByZoneId = getSidsByZoneId(i);
for (int sid :sidsByZoneId) {
mainDao.updateZoneIdAndServerTime(newZoneId,openTime, sid);
UtilLog.COMMON_LOG.info("...updateZoneId:"+sid);
}
}
sqlSession.commit();
}

public static void updateServerZone(){
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
int newZoneId = entry.getValue();

ConfigServerZone zone = Config.zoneMap.get(entry.getValue());

SqlSession sqlSession = Config.mainSqlSession;
ConfigServerZoneDao serverDao = sqlSession.getMapper(ConfigServerZoneDao.class);

for (int i : entry.getKey()) {
List<Integer> sidsByZoneId = getSidsByZoneId(i);
for (int sid :sidsByZoneId) {
serverDao.update(zone.getInternalIp(), zone.getServerIp(), zone.getPort(), zone.getDomain(),newZoneId,zone.getOpenTime(), sid);
UtilLog.COMMON_LOG.info("...updateServerZone:"+sid);
}
}
sqlSession.commit();
}

public static void updateProcessBenfuConfig(){
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
ConfigServerZone zone = Config.zoneMap.get(entry.getValue());
SqlSession sqlSession = Config.mainSqlSession;
ProcessBenfuConfigDao serverDao = sqlSession.getMapper(ProcessBenfuConfigDao.class);

for (int i : entry.getKey()) {
List<Integer> sidsByZoneId = getSidsByZoneId(i);
for (int sid :sidsByZoneId) {
serverDao.update(zone.getInternalIp(), zone.getServerIp(), zone.getPort(), sid);
UtilLog.COMMON_LOG.info("...updateProcessBenfuConfig:"+sid);
}
}
sqlSession.commit();
}

public static void deleteProcessDBSConfig(){
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
SqlSession sqlSession = Config.mainSqlSession;
ProcessDBSConfigDao serverDao = sqlSession.getMapper(ProcessDBSConfigDao.class);

for (int i : entry.getKey()) {
List<Integer> sidsByZoneId = getSidsByZoneId(i);
for (int sid :sidsByZoneId) {
serverDao.delete(sid);
UtilLog.COMMON_LOG.info("...deleteProcessDBSConfig:"+sid);
}
}
sqlSession.commit();
}

public static void deleteDictConfig(){
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
SqlSession sqlSession = Config.mainSqlSession;
DataSourceDictConfigDao serverDao = sqlSession.getMapper(DataSourceDictConfigDao.class);

for (int i : entry.getKey()) {
List<Integer> sidsByZoneId = getSidsByZoneId(i);
for (int sid :sidsByZoneId) {
serverDao.delete(sid);
UtilLog.COMMON_LOG.info("...deleteProcessDBSConfig:"+sid);
}
}
sqlSession.commit();
}

public static void deleteRedisConfig(){
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
SqlSession sqlSession = Config.mainSqlSession;
DataSourceRedisConfigDao serverDao = sqlSession.getMapper(DataSourceRedisConfigDao.class);

for (int i : entry.getKey()) {
List<Integer> sidsByZoneId = getSidsByZoneId(i);
for (int sid :sidsByZoneId) {
serverDao.delete(sid);
UtilLog.COMMON_LOG.info("...deleteRedisConfig:"+sid);
}
}
sqlSession.commit();
}

public static void deleteDataSourceConfig(){
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
SqlSession sqlSession = Config.mainSqlSession;
DataSourceConfigDao serverDao = sqlSession.getMapper(DataSourceConfigDao.class);

for (int i : entry.getKey()) {
List<Integer> sidsByZoneId = getSidsByZoneId(i);
for (int sid :sidsByZoneId) {
serverDao.delete(sid);
UtilLog.COMMON_LOG.info("...deleteRedisConfig:"+sid);
}
}
sqlSession.commit();
}

public static void updateDataSourceConfig() {
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();

SqlSession sqlSession = Config.mainSqlSession;
DataSourceConfigDao dataDao = sqlSession.getMapper(DataSourceConfigDao.class);

DataSourceConfig dataSourceConfig = dataDao.findByServerId(entry.getValue()).get(0);

for (int i : entry.getKey()) {
List<Integer> sidsByZoneId = getSidsByZoneId(i);
for (int sid :sidsByZoneId) {
dataDao.update(dataSourceConfig.getJdbc(), sid);
UtilLog.COMMON_LOG.info("...updateDataSourceConfig:"+sid);
}
}
sqlSession.commit();
}
/*
* 默认逻辑合服之前,已经完成了物理合服,否则先进行物理合服将redis数据迁移到一个服上
*/
public static boolean checkConditionBeforeLogicMerge() {
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();

String serverIp = Config.zoneMap.get(entry.getValue()).getServerIp();

List<ConfigServerZone> zoneList = new ArrayList<>();
for (ConfigServerZone zone : Config.zoneMap.values()) {
for (int sid : entry.getKey()) {
if(zone.getServerId() == sid){
zoneList.add(zone);
break;
}
}
}

for (ConfigServerZone zone : zoneList) {
if(!zone.getServerIp().equals(serverIp)){
return false;
}
}
return true;
}

}

###################################5#########################

 

package com.game2sky.deal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;

import com.game2sky.Config;
import com.game2sky.util.UtilLog;
import com.game2sky.util.Utils;

/**
* 处理本服redis数据.
*
* @author machao
* @version v0.1 2018年9月6日 下午5:14:15 machao
*/
public class DealRedis {

private static List<String> redisKeys = new ArrayList<>();
static {
List<String> fileContent = Utils.getFileContent("dealRedisKey.txt");
redisKeys = fileContent;
}

public static void dealRedis() {
UtilLog.COMMON_LOG.info("开始处理redis数据...");
for (String key : redisKeys) {
UtilLog.COMMON_LOG.info("...deal key : "+key);

if(key.startsWith("deleteall.")){
delete(key, true);
}else if(key.startsWith("deletefrom.")){
delete(key, false);
}else if(key.startsWith("merge.")){
merge(key);
}else if(key.startsWith("rename.")){
rename(key);
}else if(key.startsWith("special.")){
special(key);
}
}
}

private static void special(String key){
String[] splits = key.split("\\.");
if(splits[2].startsWith("playerShopPrice")){

Map<String,List<Integer>> priceMap = new HashMap<>();

List<Integer> serverList = new ArrayList<>();
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
serverList.addAll(entry.getKey());
serverList.add(entry.getValue());
for (int i : serverList) {
RedisTemplate<Object, Object> redisSession = Config.redisSessionMap.get(i);
String redisKey = splits[2].replace("{serverId}", i+"");
UtilLog.COMMON_LOG.info("special key : "+redisKey);
try {
Map<Object, Object> map = redisSession.opsForHash().entries(redisKey);
for (Entry<Object, Object> t : map.entrySet()) {
String itemId = (String)t.getKey();
int price = Integer.parseInt((String)t.getValue());
if(priceMap.containsKey(itemId)){
priceMap.get(itemId).add(price);
}else{
List<Integer> l = new ArrayList<Integer>();
l.add(price);
priceMap.put(itemId, l);
}
}
} catch (Exception e) {
e.printStackTrace();
UtilLog.LOG_ERROR.error("special error playerShopPrice1" + "\n" + e);
}
}

Map<String,String> priceMapTemp = new HashMap<>();
for (Entry<String,List<Integer>> t : priceMap.entrySet()) {
int sum = 0;
for (int i : t.getValue()) {
sum += i;
}
priceMapTemp.put(t.getKey(), sum/t.getValue().size()+"");
}

try {
RedisTemplate<Object, Object> toSession = Config.redisSessionMap.get(entry.getValue());
String toKey = splits[2].replace("{serverId}", entry.getValue()+"");
toSession.opsForHash().putAll(toKey, priceMapTemp);
for (int from : entry.getKey()) {
RedisTemplate<Object, Object> fromSession = Config.redisSessionMap.get(from);
String fromKey = splits[2].replace("{serverId}", from+"");
deleteKey(fromSession, fromKey);
}
} catch (Exception e) {
e.printStackTrace();
UtilLog.LOG_ERROR.error("special error playerShopPrice2" + "\n" + e);
}
}
}

private static void merge(String key){
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
int toSid = entry.getValue();
RedisTemplate<Object, Object> toSession = Config.redisSessionMap.get(toSid);
String toKey = key.split("\\.")[2].replace("{serverId}", toSid+"");

toKey = getRealKey(toKey, toSession);
String type = key.split("\\.")[1];

for (int fromSid : entry.getKey()) {
RedisTemplate<Object, Object> fromSession = Config.redisSessionMap.get(fromSid);
String fromKey = key.split("\\.")[2].replace("{serverId}", fromSid+"");
fromKey = getRealKey(fromKey, fromSession);

if("hash".equals(type)){
mergeHash(fromSession, toSession, fromKey, toKey);
}else if("set".equals(type)){
mergeSet(fromSession, toSession, fromKey, toKey);
}else if("zset".equals(type)){
mergeZset(fromSession, toSession, fromKey, toKey,fromSid,toSid);
}
}
}
private static String getRealKey(String patternKey,RedisTemplate<Object, Object> session){
if(patternKey.startsWith("ladderwar:")){
Set<Object> keys = session.keys(patternKey);
int num = 0;
String key = "";
for (Object o : keys) {
String s = ((String)o).split(":")[2];
int n = Integer.parseInt(s);
if(n > num){
num = n;
key = (String)o;
}
}
return key;
}
return patternKey;
}

private static void mergeHash(RedisTemplate<Object, Object> fromSession,RedisTemplate<Object, Object> toSession,
String fromKey,String toKey){
try {
Map<Object, Object> map = fromSession.opsForHash().entries(fromKey);

if(map.size() <= 0){
return;
}

toSession.opsForHash().putAll(toKey, map);
deleteKey(fromSession, fromKey);
UtilLog.COMMON_LOG.info("mergeHash fromkey =" +fromKey+",toKey"+toKey);
} catch (Exception e) {
UtilLog.LOG_ERROR.error("mergeHash error fromkey =" +fromKey+",toKey"+toKey + "\n" + e);
}
}

private static void mergeSet(RedisTemplate<Object, Object> fromSession,RedisTemplate<Object, Object> toSession,
String fromKey,String toKey){
try {
Set<Object> members = fromSession.opsForSet().members(fromKey);

if(members.size() <= 0){
return;
}

Object[] obts = new Object[members.size()];
members.toArray(obts);
toSession.opsForSet().add(toKey, obts);

deleteKey(fromSession, fromKey);
UtilLog.COMMON_LOG.info("mergeSet fromkey =" +fromKey+",toKey"+toKey);
} catch (Exception e) {
UtilLog.LOG_ERROR.error("mergeSet error fromkey =" +fromKey+",toKey"+toKey + "\n" + e);
}
}

private static void mergeZset(RedisTemplate<Object, Object> fromSession,RedisTemplate<Object, Object> toSession,
String fromKey,String toKey,int fromSid,int toSid){
//这里写不成通用的处理,因为每个key不一样,需要全部查出来在构造fromkey和tokey,所以只能特殊处理
if(fromKey.startsWith("secretPlaceFightTotalRank")){
Set<Object> keys = fromSession.keys(fromKey);
for (Object o : keys) {
String fkey = (String)o;

String tkey=fkey;
try {
Set<TypedTuple<Object>> rangeWithScores = fromSession.opsForZSet().rangeWithScores(fkey, 0, -1);

if(rangeWithScores.size() <= 0){
continue;
}

tkey = tkey.replace(":"+fromSid+":", ":"+toSid+":");
toSession.opsForZSet().add(tkey, rangeWithScores);

deleteKey(fromSession, fkey);
UtilLog.COMMON_LOG.info("mergeZset fkey =" +fkey+",tKey"+tkey);
} catch (Exception e) {
UtilLog.LOG_ERROR.error("mergeZset error fkey =" +fkey+",tKey"+tkey + "\n" + e);
}
}
}else{

try {
Set<TypedTuple<Object>> rangeWithScores = fromSession.opsForZSet().rangeWithScores(fromKey, 0, -1);

if(rangeWithScores.size() <= 0){
return;
}

toSession.opsForZSet().add(toKey, rangeWithScores);

deleteKey(fromSession, fromKey);
UtilLog.COMMON_LOG.info("mergeZset fromkey =" +fromKey+",toKey"+toKey);
} catch (Exception e) {
UtilLog.LOG_ERROR.error("mergeZset error fromkey =" +fromKey+",toKey"+toKey + "\n" + e);
}
}
}

private static void rename(String key){
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
int toSid = entry.getValue();
for (int fromSid : entry.getKey()) {
String replace = key.split("\\.")[2].replace("{serverId}", fromSid+"");
RedisTemplate<Object, Object> redisSession = Config.redisSessionMap.get(fromSid);
Set<Object> keys = redisSession.keys(replace);

for (Object rk : keys) {
String oldKey = (String)rk;
String newKey = oldKey;
newKey = newKey.replace(fromSid+":", toSid+":");

renameKey(redisSession, oldKey, newKey);
}
}
}

private static void renameKey(RedisTemplate<Object, Object> session, String oldKey , String newKey) {
try {
session.rename(oldKey, newKey);
UtilLog.COMMON_LOG.info("rename redis oldkey:"+oldKey+",newKey:"+newKey);
} catch (Exception e) {
UtilLog.LOG_ERROR.error("rename key error:" + oldKey + "\n" + e);
}
}

private static void delete(String key,boolean isDeleteAll) {
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
List<Integer> sids = new ArrayList<>();
sids.addAll(entry.getKey());
if(isDeleteAll){
sids.add(entry.getValue());
}

for (int sid : sids) {
String replace = key.split("\\.")[2].replace("{serverId}", sid+"");
deleteKey(Config.redisSessionMap.get(sid), replace);
}
}

private static void deleteKey(RedisTemplate<Object, Object> session, String k) {
try {
Set<Object> keys = session.keys(k);
for (Object o : keys) {
String key = (String)o;
session.delete(key);
UtilLog.COMMON_LOG.info("delete redis key:"+key);
}
} catch (Exception e) {
UtilLog.LOG_ERROR.error("error stringk:" + k + "\n" + e);
}
}
}

#########################################################

package com.game2sky.deal;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.ibatis.session.SqlSession;

import com.game2sky.Config;
import com.game2sky.dao.BenfuDao;
import com.game2sky.util.UtilLog;
import com.game2sky.util.Utils;

/**
* 删除相同战斗id数据,防止合并数据库报错.
*
* @author machao
* @version v0.1 2018年9月6日 下午5:14:15 machao
*/
public class DeleteRepeatedId {

public static List<String> repeatedKeys = new ArrayList<>();
static {
List<String> fileContent = Utils.getFileContent("deleteRepeatedId.txt");
repeatedKeys=fileContent;
}

public static void deleteRepeatedFightId() {
Entry<List<Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();

List<Integer> fromServerId = entry.getKey();
int toServerId = entry.getValue();
for (String key : repeatedKeys) {
String tableName = key.split(",")[0];
String field = key.split(",")[1];

List<Long> toFightIdList = getFightIdList(toServerId, tableName, field);
Set<Long> fightIdset = new HashSet<>(toFightIdList);

for (int from : fromServerId) {
List<Long> deleteRepeatedId = new ArrayList<>();
List<Long> fromFightIdList = getFightIdList(from, tableName,
field);
for (long fid : fromFightIdList) {
boolean add = fightIdset.add(fid);
if (!add) {
deleteRepeatedId.add(fid);
}
}

if (deleteRepeatedId.size() > 0) {
deleteRepeat(from, deleteRepeatedId, tableName, field);
}
}
}
}
private static List<Long> getFightIdList(int serverId,String table,String field){
SqlSession sqlSession = Config.dbSessionMap.get(serverId);
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);
List<Long> findFightId = benfuDao.findFightId(field, table);
return findFightId;
}
private static void deleteRepeat(int serverId,List<Long> fightIdList,String table,String field){
SqlSession sqlSession = Config.dbSessionMap.get(serverId);
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);
benfuDao.deleteRepeatedId(table, field, fightIdList);
sqlSession.commit();
UtilLog.COMMON_LOG.info("delete repeated fightId fromServerId:" + serverId + ",tableName:"+ table + ",repeatSize:"+fightIdList.size() +",repeatId:" + fightIdList);
}

}

######################################################

package com.game2sky.deal;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.ibatis.session.SqlSession;

import com.alibaba.fastjson.TypeReference;
import com.game2sky.Config;
import com.game2sky.dao.BenfuDao;
import com.game2sky.util.JsonUtils;
import com.game2sky.util.UtilLog;
import com.game2sky.util.Utils;

/**
* @author wangby
* @version v0.1 2019/3/22 16:20 wangby
*/
public class VerifyMysql {
private final static String FILE_ENCODING = "UTF-8";
private final static String[] FILE_SUFFIX = {"after", "pre"};

public static boolean verifyMysql(boolean mergeAfter) {
UtilLog.COMMON_LOG.info("...开始校验数据:" + mergeAfter);
List <Integer> allServerIds = getAllServerIds(mergeAfter);
UtilLog.LOG_ERROR.error("...开始校验数据: allServerIds=" + JsonUtils.toGson(allServerIds));

Map <String, Long> tableCountMap = new HashMap <>();
for (int serverId : allServerIds) {
tableCountMap = countTableFromDB(serverId);
saveToFile(mergeAfter, serverId, tableCountMap);
}

if (mergeAfter) {
return verifyData(tableCountMap);
}
return true;
}

private static List <Integer> getAllServerIds(boolean mergeAfter) {
List <Integer> allServerIds = new ArrayList <>();
Map.Entry <List <Integer>, Integer> entry = Config.fromToServerIdMap.entrySet().iterator().next();
allServerIds.add(entry.getValue());
if (!mergeAfter) {
allServerIds.addAll(entry.getKey());
}
return allServerIds;
}

public static boolean verifyData(Map <String, Long> finalTableCountMap) {
boolean verifyPass = true;
Map <String, Long> totalTableCountMap;

try {
List <Integer> allServerIds = new ArrayList <>();
Map.Entry <List <Integer>, Integer> entryMap = Config.fromToServerIdMap.entrySet().iterator().next();
allServerIds.add(entryMap.getValue());
allServerIds.addAll(entryMap.getKey());
int toServerId = entryMap.getValue();
totalTableCountMap = readMergePreFile(allServerIds);

// 校验数据
if (totalTableCountMap.size() != finalTableCountMap.size()) {
UtilLog.LOG_ERROR.error("合并前后表数量不同!" + JsonUtils.toGson(Config.fromToServerIdMap) + "," + totalTableCountMap.size() + "-" + finalTableCountMap.size());
verifyPass = false;
}

Map <String, Long> compareTableMap = totalTableCountMap.size() > finalTableCountMap.size() ? totalTableCountMap : finalTableCountMap;
for (Map.Entry <String, Long> entry : compareTableMap.entrySet()) {
String tableName = entry.getKey();
Long finalCount = finalTableCountMap.get(tableName);
Long totalCount = totalTableCountMap.get(tableName);
if (finalCount == null || totalCount == null) {
UtilLog.LOG_ERROR.error("toServerId=" + toServerId + ",数据表不存在:" + tableName + ",finalCount=" + finalCount + ",totalCount=" + totalCount);
verifyPass = false;
continue;
}
if (Long.compare(finalCount, totalCount) != 0) {
UtilLog.LOG_ERROR.error("toServerId=" + toServerId + ",数据表数据丢失:" + tableName + ",finalCount=" + finalCount + ",totalCount=" + totalCount);
verifyPass = false;
continue;
} else {
UtilLog.COMMON_LOG.info("\t\ttoServerId=" + toServerId+ ",表[" +tableName+ "] 校验通过");
}
}
if (!verifyPass) {
UtilLog.LOG_ERROR.error("合服数据校验不通过!" + "config=" + JsonUtils.toGson(Config.fromToServerIdMap));
System.out.println("合服数据校验不通过!" + "config=" + JsonUtils.toGson(Config.fromToServerIdMap));
} else {
UtilLog.COMMON_LOG.info("合服数据校验通过!" + "config=" + JsonUtils.toGson(Config.fromToServerIdMap));
}
} catch (Exception e) {
verifyPass = false;
UtilLog.LOG_ERROR.error("合服数据校验异常!", e);
}
return verifyPass;
}

private static Map <String, Long> readMergePreFile(List <Integer> allServerIds) throws IOException {
Map <String, Long> totalTableCountMap = new HashMap <>();
for (int serverId : allServerIds) {
String pathName = getPathName(serverId, false);
String fileData = FileUtils.readFileToString(new File(pathName), FILE_ENCODING);
Map <String, Long> tableMap = JsonUtils.S2O(fileData, new TypeReference <HashMap <String, Long>>() {
});

for (Map.Entry <String, Long> entry : tableMap.entrySet()) {
String tableName = entry.getKey();
Long count = entry.getValue();
Long upCount = totalTableCountMap.get(tableName);
upCount = upCount == null ? count : (upCount + count);
totalTableCountMap.put(tableName, upCount);
}
}
return totalTableCountMap;
}

private static Map <String, Long> countTableFromDB(int serverId) {
Map <String, Long> tableCountMap = new HashMap <>();

SqlSession sqlSession = Config.dbSessionMap.get(serverId);
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);
List <String> dbTableNames = benfuDao.selectTableNames();
sqlSession.commit();
UtilLog.COMMON_LOG.info("serverId=" + serverId + ",dbTableNames.size = " + dbTableNames.size());

int index = 0;
for (String tableName : dbTableNames) {
int count = benfuDao.count(tableName);
sqlSession.commit();
tableCountMap.put(tableName, new Long(count));
++index;
UtilLog.COMMON_LOG.info("\t\t【" + index+"】 "+tableName + ".count="+count);
}
return tableCountMap;
}

private static void saveToFile(boolean mergeAfter, int serverId, Map <String, Long> tableCountMap) {
String jsonData = JsonUtils.toGson(tableCountMap);
try {
String pathName = getPathName(serverId, mergeAfter);
FileUtils.write(new File(pathName), jsonData, FILE_ENCODING, false);
UtilLog.COMMON_LOG.info("serverId=" + serverId + ",pathName = " + pathName);
} catch (Exception e) {
UtilLog.LOG_ERROR.error("合服文件保存异常!serverId="+serverId, e);
}
}

private static String getPathName(int serverId, boolean mergeAfter) {
String suffix = FILE_SUFFIX[mergeAfter ? 0 : 1];
String file = Utils.getFilePath(suffix + "_" + serverId + ".json");
return file;
}
}

 

##################################################

 

**********************************************************************

domain package

package com.game2sky.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.game2sky.publib.framework.dbs.model.entity.BaseCacheEntity;
import com.game2sky.publib.framework.dbs.annotation.Direct;
import com.game2sky.publib.framework.dbs.dao.DBSIdGenerator;
import com.game2sky.prilib.dbs.generator.BaseActivityIdGenerator;
import com.game2sky.publib.framework.dbs.annotation.EntityPriority;
import com.game2sky.prilib.dbs.model.PriEntityPriority;
/**
*
* @author CodeGenerator, don't modify this file please.
*/

@Entity
@Table(name="base_activity")
@Direct
@DBSIdGenerator(BaseActivityIdGenerator.class)
@EntityPriority(Priority=228)
public class BaseActivity extends BaseCacheEntity<Long> {

/** 基础活动唯一id */
protected Long baseActivityId;
/** 基础活动类型 */
protected Integer baseActivityType;
/** 对应的渠道(多个逗号分隔,空代表全部) */
protected String channelIds;
/** 开始时间 */
protected Long startTime;
/** 结束时间 */
protected Long endTime;
/** 生效开始时间 */
protected Long effectStartTime;
/** 生效时间段类型 */
protected Integer effectPeriodTimeType;
/** 生效时间段参数1 */
protected String effectPeriods;
/** 生效时间段参数2 */
protected String effectPeriodTime;
/** 生效结束时间 */
protected Long effectEndTime;
/** 发奖时间 */
protected Long rewardTime;
/** 基础活动运营开关 */
protected Integer onOff;
/** 基础活动展示开关 */
protected Integer isShow;
/** 页签名字 */
protected String pageName;
/** 关联url */
protected String relateUrl;
/** 页签描述 */
protected String pageDesc;
/** 背景图 */
protected String bgImage;
/** 排序 */
protected Integer sort;
/** 解锁等级 */
protected Integer unlockLevel;
/** 解锁任务id */
protected Integer unlockTaskId;
/** 活动最终大奖 */
protected String finalRewards;
/** 活动最终大奖描述 */
protected String finalRewardsText;
/** 活动自定义数据 */
protected String customData;
/** 创建时间 */
protected Long createTime;
/** 更新时间 */
protected Long updateTime;
/** 基础活动状态 */
protected Integer state;
/** 固定增加的 最后数据版本 */
protected Long modifyVersion;

public BaseActivity(){
super();
}

public BaseActivity( Long baseActivityId, Integer baseActivityType, String channelIds, Long startTime, Long endTime, Long effectStartTime, Integer effectPeriodTimeType, String effectPeriods, String effectPeriodTime, Long effectEndTime, Long rewardTime, Integer onOff, Integer isShow, String pageName, String relateUrl, String pageDesc, String bgImage, Integer sort, Integer unlockLevel, Integer unlockTaskId, String finalRewards, String finalRewardsText, String customData, Long createTime, Long updateTime, Integer state,Long modifyVersion ){
this.baseActivityId = baseActivityId;
this.baseActivityType = baseActivityType;
this.channelIds = channelIds;
this.startTime = startTime;
this.endTime = endTime;
this.effectStartTime = effectStartTime;
this.effectPeriodTimeType = effectPeriodTimeType;
this.effectPeriods = effectPeriods;
this.effectPeriodTime = effectPeriodTime;
this.effectEndTime = effectEndTime;
this.rewardTime = rewardTime;
this.onOff = onOff;
this.isShow = isShow;
this.pageName = pageName;
this.relateUrl = relateUrl;
this.pageDesc = pageDesc;
this.bgImage = bgImage;
this.sort = sort;
this.unlockLevel = unlockLevel;
this.unlockTaskId = unlockTaskId;
this.finalRewards = finalRewards;
this.finalRewardsText = finalRewardsText;
this.customData = customData;
this.createTime = createTime;
this.updateTime = updateTime;
this.state = state;
this.modifyVersion = modifyVersion;
}

public BaseActivity(Long baseActivityId ,Integer baseActivityType ,String channelIds ,Long startTime ,Long endTime ,Long effectStartTime ,Integer effectPeriodTimeType ,String effectPeriods ,String effectPeriodTime ,Long effectEndTime ,Long rewardTime ,Integer onOff ,Integer isShow ,String pageName ,String relateUrl ,String pageDesc ,String bgImage ,Integer sort ,Integer unlockLevel ,Integer unlockTaskId ,String finalRewards ,String finalRewardsText ,String customData ,Long createTime ,Long updateTime ,Integer state){
this.baseActivityId = baseActivityId;
this.baseActivityType = baseActivityType;
this.channelIds = channelIds;
this.startTime = startTime;
this.endTime = endTime;
this.effectStartTime = effectStartTime;
this.effectPeriodTimeType = effectPeriodTimeType;
this.effectPeriods = effectPeriods;
this.effectPeriodTime = effectPeriodTime;
this.effectEndTime = effectEndTime;
this.rewardTime = rewardTime;
this.onOff = onOff;
this.isShow = isShow;
this.pageName = pageName;
this.relateUrl = relateUrl;
this.pageDesc = pageDesc;
this.bgImage = bgImage;
this.sort = sort;
this.unlockLevel = unlockLevel;
this.unlockTaskId = unlockTaskId;
this.finalRewards = finalRewards;
this.finalRewardsText = finalRewardsText;
this.customData = customData;
this.createTime = createTime;
this.updateTime = updateTime;
this.state = state;
this.modifyVersion = modifyVersion;
}

@Transient
@Override
public Long getUniqDBSId() {
return baseActivityId;
}

@Override
public void setUniqDBSId(Long id) {
}

@Id
@Column
public Long getBaseActivityId() {
return this.baseActivityId;
}

public void setBaseActivityId(Long baseActivityId) {
this.baseActivityId = baseActivityId;
}
@Column
public Integer getBaseActivityType() {
return this.baseActivityType;
}

public void setBaseActivityType(Integer baseActivityType) {
this.baseActivityType = baseActivityType;
}
@Column
public String getChannelIds() {
return this.channelIds;
}

public void setChannelIds(String channelIds) {
this.channelIds = channelIds;
}
@Column
public Long getStartTime() {
return this.startTime;
}

public void setStartTime(Long startTime) {
this.startTime = startTime;
}
@Column
public Long getEndTime() {
return this.endTime;
}

public void setEndTime(Long endTime) {
this.endTime = endTime;
}
@Column
public Long getEffectStartTime() {
return this.effectStartTime;
}

public void setEffectStartTime(Long effectStartTime) {
this.effectStartTime = effectStartTime;
}
@Column
public Integer getEffectPeriodTimeType() {
return this.effectPeriodTimeType;
}

public void setEffectPeriodTimeType(Integer effectPeriodTimeType) {
this.effectPeriodTimeType = effectPeriodTimeType;
}
@Column
public String getEffectPeriods() {
return this.effectPeriods;
}

public void setEffectPeriods(String effectPeriods) {
this.effectPeriods = effectPeriods;
}
@Column
public String getEffectPeriodTime() {
return this.effectPeriodTime;
}

public void setEffectPeriodTime(String effectPeriodTime) {
this.effectPeriodTime = effectPeriodTime;
}
@Column
public Long getEffectEndTime() {
return this.effectEndTime;
}

public void setEffectEndTime(Long effectEndTime) {
this.effectEndTime = effectEndTime;
}
@Column
public Long getRewardTime() {
return this.rewardTime;
}

public void setRewardTime(Long rewardTime) {
this.rewardTime = rewardTime;
}
@Column
public Integer getOnOff() {
return this.onOff;
}

public void setOnOff(Integer onOff) {
this.onOff = onOff;
}
@Column
public Integer getIsShow() {
return this.isShow;
}

public void setIsShow(Integer isShow) {
this.isShow = isShow;
}
@Column
public String getPageName() {
return this.pageName;
}

public void setPageName(String pageName) {
this.pageName = pageName;
}
@Column
public String getRelateUrl() {
return this.relateUrl;
}

public void setRelateUrl(String relateUrl) {
this.relateUrl = relateUrl;
}
@Column
public String getPageDesc() {
return this.pageDesc;
}

public void setPageDesc(String pageDesc) {
this.pageDesc = pageDesc;
}
@Column
public String getBgImage() {
return this.bgImage;
}

public void setBgImage(String bgImage) {
this.bgImage = bgImage;
}
@Column
public Integer getSort() {
return this.sort;
}

public void setSort(Integer sort) {
this.sort = sort;
}
@Column
public Integer getUnlockLevel() {
return this.unlockLevel;
}

public void setUnlockLevel(Integer unlockLevel) {
this.unlockLevel = unlockLevel;
}
@Column
public Integer getUnlockTaskId() {
return this.unlockTaskId;
}

public void setUnlockTaskId(Integer unlockTaskId) {
this.unlockTaskId = unlockTaskId;
}
@Column
public String getFinalRewards() {
return this.finalRewards;
}

public void setFinalRewards(String finalRewards) {
this.finalRewards = finalRewards;
}
@Column
public String getFinalRewardsText() {
return this.finalRewardsText;
}

public void setFinalRewardsText(String finalRewardsText) {
this.finalRewardsText = finalRewardsText;
}
@Column
public String getCustomData() {
return this.customData;
}

public void setCustomData(String customData) {
this.customData = customData;
}
@Column
public Long getCreateTime() {
return this.createTime;
}

public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
@Column
public Long getUpdateTime() {
return this.updateTime;
}

public void setUpdateTime(Long updateTime) {
this.updateTime = updateTime;
}
@Column
public Integer getState() {
return this.state;
}

public void setState(Integer state) {
this.state = state;
}
@Column
public Long getModifyVersion() {
return this.modifyVersion;
}

public void setModifyVersion(Long modifyVersion) {
this.modifyVersion = modifyVersion;
}

@Transient
@Override
public String getDBNameSuffix() {
return "player";
}

@Override
public String toString() {
return "BaseActivity[baseActivityId=" + baseActivityId + ",baseActivityType=" + baseActivityType + ",channelIds=" + channelIds + ",startTime=" + startTime + ",endTime=" + endTime + ",effectStartTime=" + effectStartTime + ",effectPeriodTimeType=" + effectPeriodTimeType + ",effectPeriods=" + effectPeriods + ",effectPeriodTime=" + effectPeriodTime + ",effectEndTime=" + effectEndTime + ",rewardTime=" + rewardTime + ",onOff=" + onOff + ",isShow=" + isShow + ",pageName=" + pageName + ",relateUrl=" + relateUrl + ",pageDesc=" + pageDesc + ",bgImage=" + bgImage + ",sort=" + sort + ",unlockLevel=" + unlockLevel + ",unlockTaskId=" + unlockTaskId + ",finalRewards=" + finalRewards + ",finalRewardsText=" + finalRewardsText + ",customData=" + customData + ",createTime=" + createTime + ",updateTime=" + updateTime + ",state=" + state + ",modifyVersion=" + modifyVersion + ",]";
}

@Transient
@Override
public int getEntityPriority()
{
return PriEntityPriority.BaseActivityPriority;
}

@Transient
@Override
public String getEnitityClassName()
{
return "BaseActivity";
}

}

 

******************************************************************

util package

package com.game2sky.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

/**
* TODO ADD FUNCTION_DESC.
*
* @author machao
* @version v0.1 2018年9月7日 下午3:55:13 machao
*/
public class HttpUtil {

public static String httpPost(String url, int timeout, Map<String, String> paramMap) throws HttpException,
IOException {

List<NameValuePair> valueList = new ArrayList<NameValuePair>();
Iterator<String> it = paramMap.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
String value = paramMap.get(key);
NameValuePair nv = new NameValuePair(key, value);
valueList.add(nv);
}

NameValuePair[] valueArray = valueList.toArray(new NameValuePair[0]);

HttpClient client = new HttpClient();
client.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);

PostMethod method = new PostMethod(url);

method.getParams().setContentCharset("UTF-8");
if (timeout > 0) {
client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
}
method.setRequestBody(valueArray);

int status = client.executeMethod(method);
if (status != HttpStatus.SC_OK) {
System.out.println(status);
return null;
}
String response = method.getResponseBodyAsString();

return response;
}

public static String httpGet(String url) throws HttpException, IOException {

String response = null;
HttpClient client = new HttpClient();
client.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);

GetMethod method = new GetMethod(url);

int status = client.executeMethod(method);
if (status != HttpStatus.SC_OK) {
return response;
}

response = method.getResponseBodyAsString();

return response;
}

public static void main(String[] args) throws HttpException, IOException {
String httpPost = httpGet("http://172.16.1.96:8080/self/refreshConfigCache");
System.out.println(httpPost);

String s = "{\"code\":0}";
System.out.println(s);
System.out.println(s .equals(httpPost) );
}
}

##########################################################

package com.game2sky.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.ArrayList;
import java.util.List;

public class JsonUtils {

private static ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

public static String toJascksonJson(Object object) {
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
UtilLog.LOG_ERROR.error("写入json失败," + object.getClass());
return "";
}
}

public static <T> T jacksonParseString(String json, Class <T> clazz) {
try {
return mapper.readValue(json, clazz);
} catch (Exception e) {
UtilLog.LOG_ERROR.error("读取json失败,json=" + json + ",class=" + clazz, e);
return null;
}
}

public static <T> List <T> jacksonParseList(String json, Class <T> clazz) {
try {
List <T> list = new ArrayList <T>();
if (StringUtils.isEmpty(json)) {
return list;
}
List jsonList = mapper.readValue(json, List.class);
for (Object o : jsonList) {
T t = jacksonParseString(o.toString(), clazz);
list.add(t);
}
return list;
// return mapper.readValue(json,new TypeReference<List<T>>(){});
} catch (Exception e) {
UtilLog.LOG_ERROR.error("读取jsonList失败,json=" + json + ",class=" + clazz, e);
return null;
}
}


private static Gson gson = new GsonBuilder().serializeNulls().create();

public static String toGson(Object o) {
return O2S(o);
}

public static String O2S(Object o) {
return JSON.toJSONString(o);
}

public static String O2SWithClass(Object o) {
return JSON.toJSONString(o, SerializerFeature.WriteClassName, SerializerFeature.IgnoreNonFieldGetter);
}

public static <T> T S2O(String s, Class <T> clazz) {
if (StringUtils.isEmpty(s)) {
return null;
}
return JSON.parseObject(s, clazz);
}

public static <T> T S2O(String s, TypeReference <T> type) {
if (StringUtils.isEmpty(s)) {
return null;
}
return JSON.parseObject(s, type);
}

public static <T> List <T> S2Arr(String s, Class <T> clazz) {
if (StringUtils.isEmpty(s)) {
return null;
}
return JSON.parseArray(s, clazz);
}
}

 

##############################################

 

package com.game2sky.util;

import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisAccessor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;

/**
* TODO ADD FUNCTION_DESC.
*
* @author machao
* @version v0.1 2018年9月4日 下午4:01:06 machao
*/
public class RedisTemplateFactory {

public static RedisTemplate<Object, Object> openSession(String host, int port, String pass) {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();

JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(300);
jedisPoolConfig.setMaxTotal(3000);
jedisPoolConfig.setTimeBetweenEvictionRunsMillis(-1);
jedisPoolConfig.setMinEvictableIdleTimeMillis(18000000);
jedisPoolConfig.setTestOnBorrow(true);
jedisPoolConfig.setMaxWaitMillis(-1);
JedisShardInfo info = new JedisShardInfo(host, port);
info.setPassword(pass);
info.setSoTimeout(18000000);
// info.setTimeout(18000000);
JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
connectionFactory.setHostName(host);
connectionFactory.setPort(port);
connectionFactory.setPassword(pass);
connectionFactory.setPoolConfig(jedisPoolConfig);
connectionFactory.afterPropertiesSet();
connectionFactory.setTimeout(18000000);
connectionFactory.setShardInfo(info);
stringRedisTemplate.setConnectionFactory(connectionFactory);
stringRedisTemplate.afterPropertiesSet();
// System.out.println(" RedisTemplateFactory "+stringRedisTemplate.toString());
return (RedisTemplate<Object, Object>)((RedisAccessor)stringRedisTemplate);
}
}

 

###########################################################

 

package com.game2sky.util;

import java.security.NoSuchAlgorithmException;

import javax.crypto.NoSuchPaddingException;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import com.game2sky.dao.BenfuDao;
import com.game2sky.publib.framework.util.BlowfishUtils;
import com.hutong.supersdk.common.util.EncryptUtil;


/**
* TODO ADD FUNCTION_DESC.
*
* @author machao
* @version v0.1 2018年9月4日 下午12:31:39 machao
*/
public class SqlSessionFactoryJava {

public static SqlSession openSessionByJava(String driver, String url, String usr, String pass,boolean needEncrypt) {
// 构建数据库连接池
PooledDataSource dataSource = new PooledDataSource();
dataSource.setDriver(driver);
dataSource.setUrl(url);
dataSource.setUsername(usr);
if(needEncrypt){
BlowfishUtils u;
try {
u = new BlowfishUtils(Utils.getParams("screctKey"));
String password = u.decrypt(pass);
dataSource.setPassword(password);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// dataSource.setPassword(EncryptUtil.toMixedEncrypt(pass));
}else{
dataSource.setPassword(pass);
}

// 构建数据库事务
TransactionFactory transactionFactory = new JdbcTransactionFactory();
// 构建mybatis环境
Environment environment = new Environment("development", transactionFactory, dataSource);
// 构建配置环境
Configuration configuration = new Configuration(environment);
configuration.setCacheEnabled(false);
configuration.setLocalCacheScope(LocalCacheScope.STATEMENT);
// 注册别名
// configuration.getTypeAliasRegistry().registerAlias("user", User.class);
// 加入映射器对象
configuration.addMapper(BenfuDao.class);
// 构建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
return sqlSessionFactory.openSession();
}

}

 

##########################################################

package com.game2sky.util;

import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
* TODO ADD FUNCTION_DESC.
*
* @author machao
* @version v0.1 2018年8月30日 下午3:57:12 machao
*/
public class SqlSessionFactoryUtil {
public static SqlSessionFactory getSqlSessionFactory(String path) {
SqlSessionFactory sqlSessionFactory = null;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(path);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
return sqlSessionFactory;
}

public static SqlSession openSession(String path) {
return getSqlSessionFactory(path).openSession();
}
}

###############################################

 

package com.game2sky.util;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {
public static String trim(String str) {
if (str == null) {
str = "";
} else {
str = str.trim();
}
if (str.length() == 0) {
return str;
}

if (str.charAt(0) == '"') {
str = str.substring(1);
}

if (str.charAt(str.length() - 1) == '"') {
str = str.substring(0, str.length() - 1);
}

return str;
}

public static String[] getStringList(String str) {
str = trim(str);
if (str.endsWith(",")) {
str = str.substring(0, str.length() - 1);
}
String sep = ",";
if (str.indexOf(':') >= 0) {
sep = ":";
}
return str.split(sep);
}

public static String[] getStringList(String str, String sep) {
str = trim(str);
return str.split(sep);
}

public static int[] getIntArray(String str, String sep) {
String[] prop = getStringList(str, sep);
if(prop == null || prop.length <= 0) {
return new int[0];
}
List<Integer> tmp = new ArrayList<Integer>();
for (int i = 0; i < prop.length; i++) {
if(prop[i].isEmpty()) {
continue;
}
try {
int r = Integer.parseInt(prop[i]);
tmp.add(r);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
int[] ints = new int[tmp.size()];
for (int i = 0; i < tmp.size(); i++) {
ints[i] = tmp.get(i);
}
return ints;
}

public static List<Integer> getIntList(String str, String sep) {
List<Integer> tmp = new ArrayList<Integer>();
if (str == null || str.trim().equals("")) {
return tmp;
}
String[] prop = getStringList(str, sep);
if(prop == null || prop.length <= 0) {
return tmp;
}
for (int i = 0; i < prop.length; i++) {
if(prop[i].isEmpty()) {
continue;
}
try {
int r = Integer.parseInt(prop[i]);
tmp.add(r);
} catch (Exception e) {
e.printStackTrace();
}
}
return tmp;
}

public static String join(int[] strs, String sep) {
StringBuffer buffer = new StringBuffer();
buffer.append(strs[0]);
for (int i = 1; i < strs.length; i++) {
buffer.append(sep).append(strs[i]);
}
return buffer.toString();
}

public static String join(Object[] strs, String sep) {
StringBuffer buffer = new StringBuffer();
buffer.append(strs[0]);
for (int i = 1; i < strs.length; i++) {
buffer.append(sep).append(strs[i]);
}
return buffer.toString();
}

/**
* 倒序连接
* @param strs
* @param sep
* @return
*/
public static String reverseJoin(Object[] strs, String sep) {
StringBuffer buffer = new StringBuffer();
for (int i = strs.length-1; i > 0; i--) {
buffer.append(strs[i]).append(sep);
}
buffer.append(strs[0]);
return buffer.toString();
}

public static double[] getDoubleList(String str) {
String[] prop = getStringList(str);
if(prop == null || prop.length <= 0) {
return new double[0];
}
double[] ds = new double[prop.length];
for (int i = 0; i < ds.length; i++) {
if(prop[i].isEmpty()) {
continue;
}
ds[i] = Double.parseDouble(prop[i]);
}
return ds;
}

public static List<String> getListBySplit(String str, String split) {
List<String> list = new ArrayList<String>();
if (str == null || str.trim().equalsIgnoreCase(""))
return null;
String[] strs = str.split(split);
for (String temp : strs) {
if (temp != null && !temp.trim().equalsIgnoreCase("")) {
list.add(temp.trim());
}
}
return list;
}

public static int[] getIntList(String str) {
String[] prop = getStringList(str);
if(prop == null || prop.length <= 0) {
return new int[0];
}
List<Integer> tmp = new ArrayList<Integer>();
for (int i = 0; i < prop.length; i++) {
if(prop[i].isEmpty()) {
continue;
}
try {
String sInt = prop[i].trim();
if (sInt.length() < 20) {
int r = Integer.parseInt(prop[i].trim());
tmp.add(r);
}
} catch (Exception e) {
}
}
int[] ints = new int[tmp.size()];
for (int i = 0; i < tmp.size(); i++) {
ints[i] = tmp.get(i);
}
return ints;

}

public static List<Integer> getIntListArray(String str) {
List<Integer> tmp = new ArrayList<Integer>();
String[] prop = getStringList(str);
if(prop == null || prop.length <= 0) {
return tmp;
}
for (int i = 0; i < prop.length; i++) {
if(prop[i].isEmpty()) {
continue;
}
try {
String sInt = prop[i].trim();
if (sInt.length() < 20) {
int r = Integer.parseInt(prop[i].trim());
tmp.add(r);
}
} catch (Exception e) {
}
}
return tmp;
}

public static String toWrapString(Object obj, String content) {
if (obj == null) {
return "null";
} else {
return obj.getClass().getName() + "@" + obj.hashCode() + "[\r\n" + content + "\r\n]";
}
}

// 将1,2,3和{1,2,3}格式的字符串转化为JDK的bitset
// 考虑了两边是否有{},数字两边是否有空格,是否合法数字
public static BitSet bitSetFromString(String str) {
if (str == null) {
return new BitSet();
}
if (str.startsWith("{")) {
str = str.substring(1);
}
if (str.endsWith("}")) {
str = str.substring(0, str.length() - 1);
}
int[] ints = getIntList(str);
BitSet bs = new BitSet();
for (int i : ints) {
bs.set(i);
}
return bs;
}

public static boolean hasExcludeChar(String str) {
if (str != null) {
char[] chs = str.toCharArray();
for (int i = 0; i < chs.length; i++) {

if (Character.getType(chs[i]) == Character.PRIVATE_USE) {

return true;
}

}
}
return false;
}

public static String replaceSql(String str) {
if (str != null) {
return str.replaceAll("'", "’").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
}
return "";
}

/**
* 判断两个字符串是否相等
*
* @param s1
* @param s2
* @return true,字符串相等;false,字符串不相等
*/
public static boolean isEquals(String s1, String s2) {
if (s1 != null) {
return s1.equals(s2);
}
if (s2 != null) {
return false;
}
// 两个字符串都是null
return true;
}

/**
* 将obj转变为String表示
*
* @param obj
* @param excludes
* @return
*/
public static String obj2String(Object obj, Map<String, Boolean> excludes) {
BaseReflectionToStringBuilder _builder = new BaseReflectionToStringBuilder(obj,
ToStringStyle.SHORT_PREFIX_STYLE, excludes);
return _builder.toString();
}

/**
* 重载ReflectionToStringBuilder,用于将BaseMessage用字符串表示,但是不处理buf字段
*
*
*
*/
private static class BaseReflectionToStringBuilder extends ReflectionToStringBuilder {
private final Map<String, Boolean> excludes;

public BaseReflectionToStringBuilder(Object object, ToStringStyle style, Map<String, Boolean> excludes) {
super(object, style);
this.excludes = excludes;
}

@Override
protected boolean accept(Field field) {
boolean _accepted = true;
if (this.excludes != null) {
_accepted = this.excludes.get(field.getName()) == null;
}
return super.accept(field) && _accepted;
}
}

/**
* 判断字符串是否时数字
*
* @param text
* @return
*/
public static boolean isDigit(String text) {
String reg = "[-]*[\\d]+[\\.\\d+]*";
Pattern pat = Pattern.compile(reg);
Matcher mat = pat.matcher(text);
return mat.matches();
}

/**
* 判断一句话是否是汉语
*
* @param text
* @return
*/
public static boolean isChiness(String text) {
String reg = "[\\w]*[\\u4e00-\\u9fa5]+[\\w]*";
Pattern pat = Pattern.compile(reg);
Matcher mat = pat.matcher(text);
boolean result = mat.matches();
return result;
}

/**
* 判断单个字符是否是汉语
*
* @param cha
* @return
*/
public static boolean isChineseChar(char cha) {
String reg = "[\\u4e00-\\u9fa5]";
Pattern pat = Pattern.compile(reg);
String text = Character.toString(cha);
Matcher mat = pat.matcher(text);
boolean result = mat.matches();
return result;
}

/**
* 判断字符是否是字母(包括大小写)或者数字
*
* @param cha
* @return
*/
public static boolean isLetterAndDigit(String cha) {
String reg = "[\\w]+";
Pattern pat = Pattern.compile(reg);
Matcher mat = pat.matcher(cha);
boolean result = mat.matches();
return result;
}

/**
* 返回字符串中汉字的数量
*
* @param test
* @return
*/
public static int getChineseCount(String test) {
int count = 0;
boolean tempResult = false;
for (int i = 0; i < test.length(); i++) {
char cha = test.charAt(i);
tempResult = isChineseChar(cha);
if (tempResult) {
count++;
}
}
return count;
}

/**
* 返回字符串中字母和数字的个数,其中字母包括大小写
*
* @param text
* @return
*/
public static int getLetterAndDigitCount(String text) {
int count = 0;
boolean tempResult = false;
for (int i = 0; i < text.length(); i++) {
tempResult = isLetterAndDigit(text);
if (tempResult) {
count++;
}
}
return count;
}

/**
* 判断字符串是否为空
*
* @param str
* @return true,字符串是空的;false,字符串不是空的
*/
public static boolean isEmpty(String str) {
if (str == null || (str.trim().length() == 0)) {
return true;
}
return false;
}

/**
* 将字符串首字母大写
*
* @param s
* @return
*/
public static String upperCaseFirstCharOnly(String s) {
if (s == null || s.length() < 1) {
return s;
}
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}

/**
* 将字符串按小括号()拆分成数组
*
* @param src
* @return
*/
public static String[] bracketToArray(String src) {
if (StringUtils.isEmpty(src)) {
throw new IllegalArgumentException("source string is null or empty");
}
List<String> strList = new ArrayList<String>();
Pattern pattern = Pattern.compile("(\\()(.*?)(\\))");
Matcher matcher = pattern.matcher(src);
while (matcher.find()) {
strList.add(matcher.group().replaceAll("\\(|\\)", ""));
}
if (strList.size() == 0) {
throw new IllegalArgumentException("source string's format is not suitable");
}
return strList.toArray(new String[strList.size()]);
}

/**
* 合并两个数组
*
* @param arr1
* @param arr2
* @return
*/
public static String[] mergeArray(String[] arr1, String[] arr2) {
int len = arr1.length + arr2.length;
String[] arr = new String[len];
int i = 0;
for (String str : arr1) {
arr[i] = str;
i++;
}

for (String str : arr2) {
arr[i] = str;
i++;
}

return arr;
}

/**
* 分割字符串。不同于{@link String#split(String)},本方法不用正则匹配。
*
* @param str 要分割的字符串
* @param delimiter 分隔符
* @return 分割后的字符串数组
*/
public static String[] split(String str, String delimiter) {
if (str == null) {
return new String[0];
}
if (delimiter == null) {
return new String[] { str };
}
List<String> result = new ArrayList<String>();
if ("".equals(delimiter)) {
for (int i = 0; i < str.length(); i++) {
result.add(str.substring(i, i + 1));
}
} else {
int pos = 0;
int delPos = 0;
while ((delPos = str.indexOf(delimiter, pos)) != -1) {
result.add(str.substring(pos, delPos));
pos = delPos + delimiter.length();
}
if (str.length() > 0 && pos <= str.length()) {
// Add rest of String, but not in case of empty input.
result.add(str.substring(pos));
}
}
return result.toArray(new String[result.size()]);
}

/**
* 连接字符串。不同于{@link String#split(String)},本方法不用正则匹配。
*
* @param str 要分割的字符串
* @param delimiter 分隔符
* @return 分割后的字符串数组
*/
public static String connenct(String delimiter, Object... str) {
if (str == null) {
return "";
}
if (delimiter == null || "".equals(delimiter)) {
return Arrays.toString(str);
}
StringBuffer newStr = new StringBuffer("");
for (int i = 0; i < str.length; i++) {
if (i == str.length - 1) {
newStr.append(str[i]);
break;
}
newStr.append(str[i]).append(delimiter);
}
return newStr.toString();
}

/**
* 将字符串转换成map
*
* @param param
* @param regex1 总拆分字符
* @param regex2 key和value的拆分字符
* @return
*/
public static Map<String, String> parseKVStringToMap(String param, String regex1, String regex2) {
if (isEmpty(param)) {
return Collections.emptyMap();
}
Map<String, String> map = new HashMap<>();
String[] array = param.split(regex1);
for (String str : array) {
String[] s = str.split(regex2);
map.put(s[0], s[1]);
}
return map;
}
private static final short SHORT_DEFAULT_VALUE = 0;
public static short getShort(Object obj) {
return getShort(obj, SHORT_DEFAULT_VALUE);
}

public static short getShort(Object obj, short defValue) {
if(obj == null) {
return defValue;
}
if(obj instanceof Number) {
return ((Number)obj).shortValue();
}
return getShort(String.valueOf(obj), defValue);
}

/**
* 解析出错,返回-1
*
* @param str
* @return
*/
public static short getShort(String str) {
return getShort(str, SHORT_DEFAULT_VALUE);
}

/**
* 解析出错,返回defValue
*
* @param str
* @return
*/
public static short getShort(String str, short defValue) {
if(str == null || str.isEmpty()) {
return defValue;
}
try {
return Short.parseShort(str);
} catch (NumberFormatException e) {
return defValue;
}
}

//----------------------------

public static int getInt(Object obj) {
return getInt(obj, -1);
}

public static int getInt(Object obj, int defValue) {
if(obj == null) {
return defValue;
}
if(obj instanceof Integer) {
return ((Integer)obj).intValue();
}
return getInt(String.valueOf(obj), defValue);
}

/**
* 解析出错,返回-1
*
* @param str
* @return
*/
public static int getInt(String str) {
return getInt(str, -1);
}

/**
* 解析出错,返回defValue
*
* @param str
* @return
*/
public static int getInt(String str, int defValue) {
if(str == null || str.isEmpty()) {
return defValue;
}
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return defValue;
}
}

public static long getLong(Object obj) {
return getLong(obj, -1L);
}

/**
* 解析出错,返回-1
*
* @param str
* @return
*/
public static long getLong(String str) {
return getLong(str, -1L);
}

public static long getLong(Object obj, long defValue) {
if(obj == null) {
return defValue;
}
if(obj instanceof Long) {
return ((Long)obj).longValue();
}
return getLong(String.valueOf(obj), defValue);
}

/**
* 解析出错,返回-1
*
* @param str
* @return
*/
public static long getLong(String str, long defValue) {
if(str == null || str.isEmpty()) {
return defValue;
}
try {
return Long.parseLong(str);
} catch (NumberFormatException e) {
return defValue;
}
}

/**
* 解析出错,返回-1
*
* @param str
* @return
*/
public static float getFloat(String str) {
float result = 0;
try {
result = Float.parseFloat(str);
} catch (NumberFormatException e) {
result = -1;
}
return result;
}

// /**
// * 设置默认分隔符
// *
// * @param str
// * @return
// */
// public static List<List<String>> parseStr(String str) {
// return parseStr(str, ";", ",");
// }
//
// /**
// * 设置默认分隔符
// *
// * @param str
// * @return
// */
// public static List<List<Integer>> parseInt(String str) {
// return parseInt(str, ";", ",");
// }
//
// /**
// * 设置默认分隔符
// *
// * @param str
// * @return
// */
// public static List<List<Long>> parseLong(String str) {
// return parseLong(str, ";", ",");
// }

/**
* 拼接字符串
*
* @param list
* @param split
* @return
*/
public static String convertString(List<String> list, String split) {
StringBuilder sb = new StringBuilder();
for (String str : list) {
sb.append(str).append(split);
}
String str = sb.toString();
return str.substring(0, str.length() - split.length());
}

/**
* 默认拼接字符串
*
* @param list
* @return
*/
public static String convertString(List<String> list) {
return convertString(list, ";");
}

public static boolean isLetter(char c) {
int k = 0x80;
return c / k == 0 ? true : false;
}

public static int length(String s) {
if (s == null)
return 0;
char[] c = s.toCharArray();
int len = 0;
for (int i = 0; i < c.length; i++) {
len++;
if (!isLetter(c[i])) {
len++;
}
}
return len;
}

public static String subString(String s, int length) {
if (s == null)
return "";
if (length(s) < length) {
return s;
}
char[] c = s.toCharArray();
int len = 0;
int trueLen = 0;
for (int i = 0; i < c.length; i++) {
if (len > length - 1) {
break;
}
len++;
if (!isLetter(c[i])) {
len++;
}
trueLen++;
}
char[] values = new char[trueLen];
for (int i = 0; i < trueLen; i++) {
values[i] = c[i];
}

return new String(values);
}

public static boolean contains(int[] array, int value) {
if(array == null || array.length <= 0)
return false;
for(int a : array) {
if(a == value) {
return true;
}
}
return false;
}

}

##############################################

package com.game2sky.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class UtilLog {

private final static Log LOG = LogFactory.getLog(UtilLog.class);

public final static Logger COMMON_LOG = LogManager.getLogger("commonLogger");

public final static Logger LOG_ERROR = Logger.getLogger("errorLogger");

private static Properties properties = new Properties();

private static String onOff = "0";

private static boolean filterInterface;

/** 判断日志是否打印的关键字列表 */
private static List<String> flags = new ArrayList<String>();

public static boolean getBoolean(String key) {
return Boolean.valueOf(getString(key));
}

public static String getString(String key) {
return properties.getProperty(key);
}

public static String getString(String key, String defaultValue) {
return properties.getProperty(key, defaultValue);
}

public static Integer getInteger(String key, int defaultValue) {
return Integer.valueOf(getString(key, String.valueOf(defaultValue)));
}

public static void config(String fileName, boolean filterInterface) throws FileNotFoundException, IOException {
UtilLog.filterInterface = filterInterface;
properties.load(new FileInputStream(fileName));
List<String> tmp = new ArrayList<String>();
String[] split = properties.getProperty("keys").split(",");
for (String string : split) {
String[] split2 = string.split(";");
for (String s : split2) {
String upperCase = s.trim().toUpperCase();
if (StringUtils.isNotBlank(upperCase)) {
tmp.add(upperCase);
}
}
}
flags = tmp;
onOff = properties.getProperty("onOff");
}

/**
* 判断是否要打日志
*
* @param flag
* @return
*/
private static final boolean needLog(String flag) {
if (StringUtils.isBlank(flag)) {
return true;
} else if (onOff.equals("0")) {
return true;
} else if (onOff.equals("1") && flags.contains(flag.toUpperCase())) {
return true;
}
return false;
}

public final static void stdoutI(String content) {
LOG.info(format(content));
}

public final static void stdoutW(String content) {
LOG.warn(format(content));
}

public final static void stdoutE(String content, Throwable t) {
LOG.error(format(content), t);
}

public final static void stdoutE(String content) {
LOG.error(format(content));
}

private final static String format(String content) {
StackTraceElement stack[] = Thread.currentThread().getStackTrace();
String realFileName = "";
int realLineNum = 0;
for (int i = 0; i < stack.length; i++) {
StackTraceElement stackTraceElement = stack[i];
String className = stackTraceElement.getFileName();
if (!"Thread.java".equals(className) && !"UtilLog.java".equals(className)) {
realFileName = stackTraceElement.getFileName();
realLineNum = stackTraceElement.getLineNumber();
break;
}
}
long playerId = 0;
try {
playerId = 111111l;
} catch (Exception e) {
}
return "[" + playerId + "] (" + realFileName + ":" + realLineNum + ") " + content;
}

}

 

################################################

package com.game2sky.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.game2sky.Config;
import com.game2sky.CoreBoot;
import com.game2sky.CheckBoot;

/**
* TODO ADD FUNCTION_DESC.
*
* @author machao
* @version v0.1 2018年11月30日 下午7:29:42 machao
*/
public class Utils {
public static final String prifix = "/resource";

public static List<String> getFileContent(String fileName){
List<String> contentList = new ArrayList<>();
InputStream resourceAsStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader br = null;

try {
resourceAsStream = new FileInputStream(Utils.getFilePath(fileName));
inputStreamReader = new InputStreamReader(resourceAsStream);
br = new BufferedReader(inputStreamReader);
String str = null;
while ((str = br.readLine()) != null) {
if (str.startsWith("#") || str.startsWith("//")) {
continue;
}
if(str.trim().isEmpty()){
continue;
}
contentList.add(str);
}
} catch (Exception e) {
UtilLog.LOG_ERROR.error("load file error :" + fileName + "\n" + e.toString());
} finally {
try {
br.close();
inputStreamReader.close();
resourceAsStream.close();
} catch (IOException e) {
UtilLog.LOG_ERROR.error("close resource error" + "\n" + e.toString());
}
UtilLog.COMMON_LOG.info("fileName :"+fileName+",fileContent:"+contentList);
}
if(contentList.isEmpty()){
UtilLog.LOG_ERROR.info("contentList is empty " + fileName);
System.exit(1);
}
return contentList;
}

public static String getFilePath(String filename){
String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith("win")){
return System.getProperty("user.dir")+"\\src\\main\\resources\\"+filename;
}else{
return System.getProperty("user.dir")+prifix+"/"+filename;
}
}

//是否是内网环境
public static boolean isTest = false;

public static Properties getProperties(String filename){
Properties p = new Properties();
InputStream in = null;
try {
in = new FileInputStream(getFilePath(filename));
p.load(in);
} catch (IOException e1) {
UtilLog.LOG_ERROR.error("load properties error:"+getFilePath(filename)+",\n"+e1);
throw new RuntimeException();
}
return p;
}

public static String getFromToServerIdList(){
String fromToServerIdList = "";
fromToServerIdList = CoreBoot.run.getEnvironment().getProperty("fromToServerId");
if(fromToServerIdList == null){
fromToServerIdList = "test_fromToServerId";
}
return fromToServerIdList;
}

public static List<Integer> getRankActivityTypes(){
String rankActivityTypes = "";
rankActivityTypes = CheckBoot.getConfig().getProperty("rankActivityTypes");
if(rankActivityTypes == null){
rankActivityTypes = "10";
}
List<Integer> list = new ArrayList<>();
String[] sp = rankActivityTypes.split(",");
for (String string : sp) {
list.add(Integer.valueOf(string));
}
return list;
}

public static String getParams(String key){
String value = "";
value = CheckBoot.getConfig().getProperty(key);
return value;
}

public static String getUpdateDatabaseIp(){
String updateDatabaseIp = "";
if(Config.platformId == 1){
if(isTest){
updateDatabaseIp = "test_updateDatabaseIp";
}else{
updateDatabaseIp = "and_updateDatabaseIp";
}
}else if(Config.platformId == 2){
updateDatabaseIp = "gw_updateDatabaseIp";
}else if(Config.platformId == 3){
updateDatabaseIp = "yh_updateDatabaseIp";
}else if(Config.platformId == 4){
updateDatabaseIp = "ios_updateDatabaseIp";
}else if(Config.platformId == 5){
updateDatabaseIp = "xf_updateDatabaseIp";
}else if(Config.platformId == 6){
updateDatabaseIp = "9997_updateDatabaseIp";
}
return updateDatabaseIp;
}

public static void getServerIdMap(String ip_ServerIdMatch,String selfIp){
List<String> ip_ServerIdList = Arrays.asList(ip_ServerIdMatch.split(";"));
for (String list : ip_ServerIdList) {
Map<List<Integer>, Integer> ip_ServerIdMap = new HashMap<List<Integer>, Integer>();
if(list.split(":")[0].equals(selfIp)){
String[] split = list.split(":")[1].split(">");

List<Integer> serverIdIntList = new ArrayList<>();
for (String s : split[0].split(",")) {
if(s.contains("-")){
String[] split2 = s.split("-");
int min = Integer.parseInt(split2[0]);
int max = Integer.parseInt(split2[1]);
for (int i = min; i <= max; i++) {
serverIdIntList.add(i);
}
}else{
serverIdIntList.add(Integer.parseInt(s));
}
}
int toServerId = Integer.parseInt(split[1]);
ip_ServerIdMap.put(serverIdIntList, toServerId);

Config.fromToServerIdMapList.add(ip_ServerIdMap);
}
}
}

public static String getNWIp(String url){
String httpGet = null;
try {
httpGet = HttpUtil.httpGet(url);
} catch (Exception e) {
UtilLog.LOG_ERROR.error("获取服务器IP 失败" + url);
throw new RuntimeException();
}
if (StringUtils.isEmpty(httpGet)) {
UtilLog.LOG_ERROR.error("获取服务器IP 为空" + url);
throw new RuntimeException();
}
String selfIp = JSON.parseObject(httpGet).getString("ip");
return selfIp;
}

public static void refreshConfig(){
try {
String httpGet = HttpUtil.httpGet(Config.url);
if ("{\"code\":0}".equals(httpGet)) {
UtilLog.LOG_ERROR.error("刷新配置成功");
} else {
UtilLog.LOG_ERROR.error("刷新配置失败");
}

String httpGet1 = HttpUtil.httpGet(Config.url1);
if ("{\"code\":0}".equals(httpGet1)) {
UtilLog.LOG_ERROR.error("刷新配置成功0");
} else {
UtilLog.LOG_ERROR.error("刷新配置失败0");
}
} catch (Exception e) {
UtilLog.LOG_ERROR.error("刷新配置失败1");
}
}

public static String getUrlConfig(){
String urlConfig = "";
urlConfig = CoreBoot.run.getEnvironment().getProperty("url.config.properties");
if(urlConfig == null){
urlConfig = "url-config-test.properties";
}
return urlConfig;
}

public static String getMybatisConfigURL(){
String hibernateXml = "";
hibernateXml = CoreBoot.run.getEnvironment().getProperty("mybatis.cfg.xml");
if(hibernateXml == null){
hibernateXml = "mybatis-config-main-test.xml";
}
return hibernateXml;
}

public static String getFlag(File file){
String s = "";
InputStream in = null;
InputStreamReader inputStreamReader = null;
BufferedReader br = null;
try {
in = new FileInputStream(file);
inputStreamReader = new InputStreamReader(in);
br = new BufferedReader(inputStreamReader);
String str = null;
while ((str = br.readLine()) != null) {
if (str.startsWith("prod=")) {
s=str.split("=")[1];
break;
}
}
} catch (Exception e) {
throw new RuntimeException();
} finally {
try {
br.close();
inputStreamReader.close();
in.close();
} catch (IOException e) {
// UtilLog.Log("close resource error" + "\n" + e);
}

}
if(StringUtils.isEmpty(s)){
throw new RuntimeException();
}
return s;
}

public static int getPlatformId() {
if(System.getProperty("os.name").toLowerCase().startsWith("win")){
isTest = true;
return 1;
}

ArrayList<String> files = new ArrayList<String>();
File file = new File("/work/script");
File[] tempList = file.listFiles();

int platformId = -1;
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isFile()) {
String fileName = tempList[i].toString();
if(fileName.contains("benfu_start.sh")){

String flag = getFlag(tempList[i]).trim();

if(flag.startsWith("andr")){
platformId = 1;
}else if(flag.startsWith("gw")){
platformId = 2;
}else if(flag.startsWith("yh")){
platformId = 3;
}else if(flag.startsWith("ios")){
platformId = 4;
}else if(flag.startsWith("xianfeng")){
platformId = 5;
}else if(flag.startsWith("onlineTest")){
platformId = 6;
}else{
//内网就是benfu_start.sh
platformId = 1;
isTest = true;
}
break;
}
}
}
if(platformId == -1){
throw new RuntimeException();
}
return platformId;
}

public static void main(String[] args) {
System.out.println(getPlatformId());
}
}

############################################################

main package

package com.game2sky;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.ibatis.session.SqlSession;
import org.hibernate.cfg.Configuration;

import com.game2sky.dao.BenfuDao;
import com.game2sky.deal.DealBenfuData;
import com.game2sky.deal.DeleteRepeatedId;
import com.game2sky.util.SqlSessionFactoryJava;
import com.game2sky.util.UtilLog;
import com.game2sky.util.Utils;

/**
*
* @author limengnan
*
*/
public class Check {

public static List<String> allTableNames = null;
public static Map<String,String> tablePriKey = null;

public static void main(String[] args) {
CheckBoot.boot(Check.class, args);
//检查配置是否已经有逻辑合服的,配置有问题
checkLogicConfig();

checkMergeCondition();

System.out.println("ok!");
UtilLog.COMMON_LOG.info("ok!");

}

public static void checkMergeCondition() {

if (Config.fromToServerIdMapList.size() > 0) {
for (int i = 0; i < Config.fromToServerIdMapList.size(); i++) {
UtilLog.COMMON_LOG.info("...第" + i + "组check开始");
Config.fromToServerIdMap = Config.fromToServerIdMapList.get(i);
UtilLog.COMMON_LOG.info("...fromToServerIdMap:" + Config.fromToServerIdMap);

// 合服前校验/处理数据
// if (!DealMainServerData.checkConditionBeforeLogicMerge()) {
// UtilLog.LOG_ERROR.error("不能进行逻辑合服,需先进行物理合服。");
// System.out.println("不能进行逻辑合服,需先进行物理合服。");
// UtilLog.COMMON_LOG.info("不能进行逻辑合服,需先进行物理合服。");
// System.exit(1);
// }

//校验活动数据
if (!DealBenfuData.checkActivityBeforeLogicMerge()) {
UtilLog.LOG_ERROR.error("不能进行逻辑合服,活动数据不一致");
System.out.println("不能进行逻辑合服,活动数据不一致");
UtilLog.COMMON_LOG.info("不能进行逻辑合服,活动数据不一致");
System.exit(1);
}

//检查全服排名活动,有开启的则不能合服
if (!DealBenfuData.checkQuanfuRankActivity()) {
UtilLog.LOG_ERROR.error("不能进行逻辑合服,全服排名活动,有开启的");
System.out.println("不能进行逻辑合服,全服排名活动,有开启的");
UtilLog.COMMON_LOG.info("不能进行逻辑合服,全服排名活动,有开启的");
System.exit(1);
}

//检测是否都是一个中心服
if (!DealBenfuData.checkCenterSame()) {
UtilLog.LOG_ERROR.error("不能进行逻辑合服,要合的服务器 不在同一个中心服下");
System.out.println("不能进行逻辑合服,要合的服务器 不在同一个中心服下");
UtilLog.COMMON_LOG.info("不能进行逻辑合服,要合的服务器 不在同一个中心服下");
System.exit(1);
}
}
}

System.out.println("first condition is ok!");
UtilLog.COMMON_LOG.info("first condition is ok!");
}



private String getURL(){
Configuration configuration = new Configuration();
String hibernateXml = CoreBoot.run.getEnvironment().getProperty("mybatis.cfg.xml");
if (hibernateXml == null) {
System.out.println("读取Hibernate配置文件错误");
System.exit(1);
return null;
}
configuration.configure(Thread.currentThread().getContextClassLoader().getResource(hibernateXml));
return hibernateXml;
}

private static void checkIntenaServerGroup(){
SqlSession dictSession = null;
if(Utils.isTest){
dictSession = SqlSessionFactoryJava.openSessionByJava("com.mysql.jdbc.Driver",
"jdbc:mysql://172.16.1.51:3306/dict?useUnicode=true&amp;characterEncoding=UTF-8&amp;autoReconnect=true",
"root", "",false);
}else{
dictSession = SqlSessionFactoryJava.openSessionByJava("com.mysql.jdbc.Driver",
"jdbc:mysql://10.104.194.66:3306/dict?useUnicode=true&amp;characterEncoding=UTF-8&amp;autoReconnect=true",
"root", "1q2w3e4r1234@",false);
}

BenfuDao benfuDao = dictSession.getMapper(BenfuDao.class);
List<String> integServerGroup = benfuDao.getServerGroup("dict_integral_server");
List<String> seaFightServerGroup = benfuDao.getServerGroup("dict_union_seafight_servergroup");

HashMap<Integer, Integer> integServerMap = getIntegServerMap(integServerGroup);
HashMap<Integer, Integer> seaFightServerMap = getSeaFightServerMap(seaFightServerGroup);

Iterator<Map<List<Integer>, Integer>> iterator = Config.fromToServerIdMapList.iterator();
while(iterator.hasNext()){
Map<List<Integer>, Integer> next = iterator.next();
List<Integer> list = new ArrayList<>();
list.addAll(next.entrySet().iterator().next().getKey());
list.add(next.entrySet().iterator().next().getValue());

Set<Integer> groupSet = new HashSet<>();
for (int i : list) {
Integer integer = integServerMap.get(i);

groupSet.add(integer);
if(groupSet.size() > 1 ){
System.out.println("exit check 天梯 跨分组 error" + next);
UtilLog.COMMON_LOG.info("exit check 天梯 跨分组 error" + next);
UtilLog.LOG_ERROR.info("exit check 天梯 跨分组 error" + next);
System.exit(1);
}
}

groupSet.clear();
for (int i : list) {
Integer integer = seaFightServerMap.get(i);

groupSet.add(integer);
if(groupSet.size() > 1 ){
System.out.println("exit check 海战 跨分组 error"+next);
UtilLog.COMMON_LOG.info("exit check 海战 跨分组 error"+next);
UtilLog.LOG_ERROR.info("exit check 海战 跨分组 error"+next);
System.exit(1);
}
}
}
}

private static HashMap<Integer,Integer> getIntegServerMap(List<String> list){
int k = 0;
HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
for (String s : list) {
String[] split = s.split("-");
if(split.length > 1){
int min = Integer.parseInt(split[0]);
int max = Integer.parseInt(split[1]);
for (int i = min; i <= max; i++) {
map.put(i, k);
}
}else{
map.put(Integer.parseInt(split[0]), k);
}
k++;
}
return map;
}

private static HashMap<Integer,Integer> getSeaFightServerMap(List<String> list){
int k = 0;
HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
for (String s : list) {
List<String> asList = Arrays.asList(s.split(","));
for (String s1 : asList) {
String[] split = s1.split("-");
if(split.length > 1){
int min = Integer.parseInt(split[0]);
int max = Integer.parseInt(split[1]);
for (int i = min; i <= max; i++) {
map.put(i, k);
}
}else{
map.put(Integer.parseInt(split[0]), k);
}
}
k++;
}
return map;
}


private static void checkTableAndCreateTable(List<String> deleteTable,List<String> notDeleteTable){

for (Map<List<Integer>, Integer> map : Config.fromToServerIdMapList) {
List<String> needAddTables = new ArrayList<>();
for (Integer fromSid : map.entrySet().iterator().next().getKey()) {
SqlSession sqlSession = Config.dbSessionMap.get(fromSid);
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);
List<String> allTableNames = benfuDao.selectTableNames();

List<String> checkTableName = checkTableName(deleteTable, notDeleteTable,allTableNames);
if(checkTableName.size() > 0){
needAddTables.addAll(checkTableName);
}
}

System.out.println("add tables:"+needAddTables);
UtilLog.COMMON_LOG.info("add tables:"+needAddTables);
Integer toSid = map.entrySet().iterator().next().getValue();
SqlSession sqlSession = Config.dbSessionMap.get(toSid);
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);
for (String tableName:needAddTables) {
benfuDao.createTable(tableName);
}

}

}
public static void checkRepeatedTable(List<String> deleteTable) {
boolean isSuccess = true;
List<String> tableNames = new ArrayList<>(allTableNames);

tableNames.removeAll(deleteTable);
for (String s : DeleteRepeatedId.repeatedKeys) {
tableNames.remove(s.split(",")[0]);
}
tableNames.remove("inst_award_player");
tableNames.remove("inst_common_fight_data");
tableNames.remove("inst_union_apply");


for (String table : tableNames) {
//因为inst_arena_server_*表是每个单服独有的,其他服没有对应的表,因此不需要检查重复的数据
if(table.startsWith("inst_arena_server_")){
continue;
}
UtilLog.COMMON_LOG.info("begin checkRepeatedTable "+ table+"...");
if (Config.fromToServerIdMapList.size() > 0) {
for (int i = 0; i < Config.fromToServerIdMapList.size(); i++) {
Map<List<Integer>, Integer> map = Config.fromToServerIdMapList.get(i);
Entry<List<Integer>, Integer> next = map.entrySet().iterator().next();

String priKey = tablePriKey.get(table);

SqlSession sqlSession = Config.dbSessionMap.get(next.getValue());
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);
HashSet<Long> idset = null;
try {
idset = new HashSet<Long>(benfuDao.findFightId(priKey, table));
} catch (Exception e) {
UtilLog.COMMON_LOG.info("... continue "+table +", cannot convert to long");
System.out.println("... continue "+table +", cannot convert to long");
continue;
}

for (int j : next.getKey()) {
SqlSession sql = Config.dbSessionMap.get(j);
BenfuDao benfu = sql.getMapper(BenfuDao.class);
List<Long> idL = benfu.findFightId(priKey, table);
for (long l : idL) {
if(!idset.add(l)){
isSuccess = false;
UtilLog.COMMON_LOG.info("... error checkRepeatedTable contains "+table +",cursid:"+j+",currid:"+l);
UtilLog.LOG_ERROR.info("... error checkRepeatedTable contains "+table +",cursid:"+j+",currid:"+l);
System.out.println("... error checkRepeatedTable contains "+table +",cursid:"+j+",currid:"+l);
}
}
}
}
}
}

if(!isSuccess){
System.out.println("exit checkRepeatedTable error");
UtilLog.COMMON_LOG.info("exit checkRepeatedTable error");
UtilLog.LOG_ERROR.info("exit checkRepeatedTable error");
System.exit(1);
}

}
public static void checkLogicConfig() {
UtilLog.COMMON_LOG.info("begin checkLogicConfig...");
if (Config.fromToServerIdMapList.size() > 0) {
for (int i = 0; i < Config.fromToServerIdMapList.size(); i++) {
Map<List<Integer>, Integer> map = Config.fromToServerIdMapList.get(i);
Entry<List<Integer>, Integer> next = map.entrySet().iterator().next();
List<Integer> key = new ArrayList<Integer>(next.getKey());
key.add(next.getValue());
HashSet<Integer> set = new HashSet<Integer>();
for (int j : key) {
int zoneId = Config.zoneMap.get(j).getZoneId();
boolean add = set.add(zoneId);
if(!add){
System.out.println("exit checkLogicConfig error");
UtilLog.COMMON_LOG.info("exit checkLogicConfig error");
UtilLog.LOG_ERROR.info("exit checkLogicConfig error");
System.exit(1);
}
}
}
}
}

public static void deleteCrossDBTable(String tableName) {
UtilLog.COMMON_LOG.info("begin deleteCrossDBTable...");
if (Config.fromToServerIdMapList.size() > 0) {
for (int i = 0; i < Config.fromToServerIdMapList.size(); i++) {
Map<List<Integer>, Integer> map = Config.fromToServerIdMapList.get(i);
Entry<List<Integer>, Integer> next = map.entrySet().iterator().next();
List<Integer> key = new ArrayList<Integer>(next.getKey());
key.add(next.getValue());
for (int j : key) {
SqlSession sqlSession = Config.dbSessionMap.get(j);
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);
List<Long> selectOtherServerData = benfuDao.selectOtherServerData(tableName);

if(selectOtherServerData.size() > 0){
benfuDao.deleteRepeatedId(tableName, "playerId", selectOtherServerData);
sqlSession.commit();

UtilLog.LOG_ERROR.info("...delete :"+tableName+",currserver:"+j+",other server playerId:"+selectOtherServerData);
UtilLog.COMMON_LOG.info("...delete :"+tableName+",currserver:"+j+",other server playerId:"+selectOtherServerData);
}
}
}
}
}

public static List<String> checkTableName(List<String> deleteTable,List<String> notDeleteTable,List<String> allTables) {
List<String> tableNames = new ArrayList<>(allTables);

tableNames.removeAll(deleteTable);
tableNames.removeAll(notDeleteTable);

List<String> inst_arena_serverTableList = new ArrayList<>();
//这里是把inst_arena_server所对应的表删掉,因为在配置表中没法加,因此不考虑这些表了
if(tableNames.size() > 0){
Iterator<String> iterator = tableNames.iterator();
while(iterator.hasNext()){
String next = iterator.next();
if(next.startsWith("inst_arena_server_")){
inst_arena_serverTableList.add(next);
iterator.remove();
}
}
}

if(tableNames.size() > 0){
System.out.println("exit checkTableName error1:"+tableNames);
UtilLog.COMMON_LOG.info("exit checkTableName error1:"+tableNames);
UtilLog.LOG_ERROR.info("exit checkTableName error1:"+tableNames);
System.exit(1);
}

return inst_arena_serverTableList;
}
}

################################################

package com.game2sky;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.URL;
import java.util.Properties;

import com.game2sky.publib.framework.app.ArgsProperty;
import com.game2sky.publib.framework.app.DmcApplication;
import com.game2sky.publib.framework.boot.DmcFrameWorkBoot;
import com.game2sky.publib.framework.common.log.DmcLog;
import com.game2sky.publib.framework.common.properties.DmcConst;
import com.game2sky.publib.framework.util.FileUtils;


/**
*
* @author limengnan
*
*/
public class CheckBoot {

/** 通用配置*/
private static Properties config;

public static void boot(Class<?> clazz, String[] args) {
assignRandomPort();
CoreBoot.application = new DmcApplication(clazz);
ArgsProperty simpleCommandLinePropertySource = new ArgsProperty(args);
CoreBoot.run = CoreBoot.application.run(simpleCommandLinePropertySource);
setConfig();
// CoreBoot.bootLocalConfig();
}

public static void assignRandomPort() {
ServerSocket serverSocket = null; //读取空闲的可用端口
try {
serverSocket = new ServerSocket(0);
} catch (IOException e) {
e.printStackTrace();
}
int port = serverSocket.getLocalPort();
CoreBoot.SELF_PORT = port - 10000;// 为了配合Spring启动会把端口加10000
}

public static void setConfig() {
FileInputStream fileInputStream = null;
boolean isFileAbsolutePath = DmcApplication.isFileAbsolutePath;
String fileAbsolutePath = DmcApplication.fileAbsolutePath;
String configPath = isFileAbsolutePath ? fileAbsolutePath + File.separator + "conf.properties" : "conf.properties";
URL resource;
if (DmcApplication.isFileAbsolutePath) {
resource = FileUtils.absolutePathToURL(configPath);
} else {
resource = DmcFrameWorkBoot.class.getClassLoader().getResource(configPath);
}
DmcLog.LOG_STDOUT.info("conf.properties.path - " + configPath);
try {
fileInputStream = new FileInputStream(resource.getPath());
Properties properties = new Properties();
InputStreamReader inputStreamReader;
inputStreamReader = new InputStreamReader(fileInputStream, DmcConst.UTF8);
properties.load(inputStreamReader);
config = properties;
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
}
}
}
}

public static Properties getConfig() {
return config;
}
}

###################################################

 

package com.game2sky;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
* TODO ADD FUNCTION_DESC.
*
* @author machao
* @version v0.1 2020年11月2日 下午6:25:54 machao
*/
public class CheckServerState {

public static List<String> executeLinuxCmd(String cmd) throws IOException {
Runtime run = Runtime.getRuntime();
Process process;
List<String> list = new ArrayList<String>();
if (!System.getProperty("os.name").toLowerCase().startsWith("win")) {
// String keyWord = "javaw.exe";
// process = run.exec("cmd /c Tasklist");
process = run.exec(new String[] { "/bin/sh", "-c", cmd });
InputStream in = process.getInputStream();
BufferedReader bs = new BufferedReader(new InputStreamReader(in));
String result = null;
while ((result = bs.readLine()) != null) {
// System.out.println("job result [" + result + "]");
// if(result.toLowerCase().startsWith("javaw.exe")){
// }
list.add(result);
}
in.close();
process.destroy();
}
return list;
}

public static void main(String[] args) {
List<String> executeLinuxCmd = null;
try {
executeLinuxCmd = executeLinuxCmd("ps -ef|grep benfu");
} catch (IOException e) {
System.out.println("job execute error!!!");
}
System.out.println(executeLinuxCmd);
if (executeLinuxCmd != null) {
System.out.println(executeLinuxCmd.size());
}

}
}

##############################################

package com.game2sky;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.data.redis.core.RedisTemplate;

import com.game2sky.dao.ConfigServerZoneDao;
import com.game2sky.dao.DataSourceConfigDao;
import com.game2sky.dao.DataSourceRedisConfigDao;
import com.game2sky.domain.ConfigServerZone;
import com.game2sky.domain.DataSourceConfig;
import com.game2sky.domain.DataSourceRedisConfig;
import com.game2sky.publib.framework.common.log.DmcLog;
import com.game2sky.util.RedisTemplateFactory;
import com.game2sky.util.SqlSessionFactoryJava;
import com.game2sky.util.SqlSessionFactoryUtil;
import com.game2sky.util.Utils;

public class Config {

public static String DRIVERNAME = "com.mysql.jdbc.Driver";
public static SqlSession mainSqlSession = null;

public static Map<List<Integer>, Integer> fromToServerIdMap = new HashMap<List<Integer>, Integer>();

public static List<Map<List<Integer>, Integer>> fromToServerIdMapList = new ArrayList<Map<List<Integer>, Integer>>();

public static Map<Integer, ConfigServerZone> zoneMap = new HashMap<Integer, ConfigServerZone>();
public static Map<Integer, DataSourceRedisConfig> redisMap = new HashMap<Integer, DataSourceRedisConfig>();
public static Map<Integer, DataSourceConfig> dataSourceMap = new HashMap<Integer, DataSourceConfig>();

public static String url;
public static String url1;
public static int platformId;

public static Map<Integer, SqlSession> dbSessionMap = new HashMap<Integer, SqlSession>();

public static Map<Integer, RedisTemplate<Object, Object>> redisSessionMap = new HashMap<>();

public static List<Integer> rankActivityTypeList = new ArrayList<>();

static {
PropertyConfigurator.configure(Utils.getFilePath("log4j.properties"));
// platformId = Utils.getPlatformId();
// DmcLog.LOG_COMMON.info("platformId:" + platformId + ",isTest:" + Utils.isTest);

Properties configProperties = Utils.getProperties("config.properties");

String urlConfig = Utils.getUrlConfig();
Properties urlProperties = Utils.getProperties(urlConfig);

String getIpUrl = urlProperties.getProperty("getIpUrl");
DmcLog.LOG_COMMON.info("getIpUrl:" + getIpUrl);
url = urlProperties.getProperty("url");
url1 = urlProperties.getProperty("url1");
DmcLog.LOG_COMMON.info("url:" + url);
DmcLog.LOG_COMMON.info("url1:" + url1);
String selfIp = Utils.getNWIp(getIpUrl);
DmcLog.LOG_COMMON.info("本机ip:" + selfIp);

Utils.getServerIdMap(configProperties.getProperty(Utils.getFromToServerIdList()), selfIp);

DmcLog.LOG_COMMON.info("fromToServerIdMapList:" + fromToServerIdMapList.toString());


// 创建主服数据库连接
mainSqlSession = SqlSessionFactoryUtil.openSession(Utils.getFilePath(Utils.getMybatisConfigURL()));

ConfigServerZoneDao configServerZoneDao = Config.mainSqlSession.getMapper(ConfigServerZoneDao.class);
List<ConfigServerZone> zoneLoadAll = configServerZoneDao.loadAll();
for (ConfigServerZone zone : zoneLoadAll) {
zoneMap.put(zone.getServerId(), zone);
}
DmcLog.LOG_COMMON.info("zoneMap size :" + zoneMap.size());

DataSourceRedisConfigDao dataSourceRedisConfigDao = Config.mainSqlSession
.getMapper(DataSourceRedisConfigDao.class);
List<DataSourceRedisConfig> dataSourceLoadAll = dataSourceRedisConfigDao.loadAll();
for (DataSourceRedisConfig dataSource : dataSourceLoadAll) {
redisMap.put(dataSource.getFromServerId(), dataSource);
}
DmcLog.LOG_COMMON.info("redisMap size :" + redisMap.size());

DataSourceConfigDao dataSourceConfigDao = Config.mainSqlSession.getMapper(DataSourceConfigDao.class);
List<DataSourceConfig> dataSourceAll = dataSourceConfigDao.loadAll();
for (DataSourceConfig dataSource : dataSourceAll) {
dataSourceMap.put(dataSource.getServerId(), dataSource);
}
DmcLog.LOG_COMMON.info("dataSourceMap size :" + dataSourceMap.size());

// 创建业务服数据库连接
for (int k = 0; k < fromToServerIdMapList.size(); k++) {
Map<List<Integer>, Integer> map = fromToServerIdMapList.get(k);
Entry<List<Integer>, Integer> entry = map.entrySet().iterator().next();
for (int i : entry.getKey()) {
DataSourceConfig dataSourceConfig = dataSourceMap.get(i);
SqlSession openSessionByJava = SqlSessionFactoryJava.openSessionByJava(DRIVERNAME,
dataSourceConfig.getJdbc(), dataSourceConfig.getUsr(), dataSourceConfig.getPassword(),true);
dbSessionMap.put(i, openSessionByJava);
}
DataSourceConfig toDataSourceConfig = dataSourceMap.get(entry.getValue());
SqlSession toDbSession = SqlSessionFactoryJava.openSessionByJava(DRIVERNAME, toDataSourceConfig.getJdbc(),
toDataSourceConfig.getUsr(), toDataSourceConfig.getPassword(),true);
dbSessionMap.put(entry.getValue(), toDbSession);
}

for (int k = 0; k < fromToServerIdMapList.size(); k++) {
Map<List<Integer>, Integer> map = fromToServerIdMapList.get(k);
Entry<List<Integer>, Integer> entry = map.entrySet().iterator().next();
// 创建业务服redis连接
for (int i : entry.getKey()) {
RedisTemplate<Object, Object> redisSession = getRedisSession(i);
redisSessionMap.put(i, redisSession);
}
redisSessionMap.put(entry.getValue(), getRedisSession(entry.getValue()));
}
}

public static RedisTemplate<Object, Object> getRedisSession(int serverId) {

ConfigServerZone find = Config.zoneMap.get(serverId);

DataSourceRedisConfig findRedis = Config.redisMap.get(serverId);
if (find == null) {
DmcLog.LOG_ERROR.error(" find null" + serverId);
}
if (findRedis == null) {
DmcLog.LOG_ERROR.error(" findRedis null" + serverId);
}
RedisTemplate<Object, Object> openSession = RedisTemplateFactory.openSession(find.getInternalIp(),
findRedis.getPort(), findRedis.getPass());

return openSession;
}

}

#################################################

package com.game2sky;

import java.io.IOException;
import java.util.List;

import com.game2sky.deal.DealMainServerData;
import com.game2sky.deal.VerifyMysql;
import com.game2sky.util.UtilLog;
import com.game2sky.util.Utils;

/**
*
* @author limengnan
*
*/
public class DealMain {

public static void main(String[] args) throws IOException {
CheckBoot.boot(DealMain.class, args);
long startTime = System.currentTimeMillis();

List<String> executeLinuxCmd = CheckServerState.executeLinuxCmd("ps -ef|grep java");
for (String s : executeLinuxCmd) {
if(s.contains("benfu")){
UtilLog.COMMON_LOG.info("###本服没有停服,程序终止!");
System.out.println("###本服没有停服,程序终止!");
// return;
}
}

if (Config.fromToServerIdMapList.size() > 0) {
for (int i = 0; i < Config.fromToServerIdMapList.size(); i++) {
UtilLog.COMMON_LOG.info("...第" + i + "组开始");
Config.fromToServerIdMap = Config.fromToServerIdMapList.get(i);
UtilLog.COMMON_LOG.info("...fromToServerIdMap:" + Config.fromToServerIdMap + ",mergeAfter=" + true);

boolean pass = VerifyMysql.verifyMysql(true);
if (!pass) {
UtilLog.LOG_ERROR.error("不能进行逻辑合服,数据比较不一致");
System.exit(1);
}
//将zoneId合并并更新mysql数据源 修改ip类
DealMainServerData.updateServerZone();
DealMainServerData.updateProcessBenfuConfig();
// DealMainServerData.updateDataSourceConfig();

//删除合并数据
DealMainServerData.deleteProcessDBSConfig();
DealMainServerData.deleteDictConfig();
DealMainServerData.deleteRedisConfig();
DealMainServerData.deleteDataSourceConfig();

//检测是否修改其他主服configServerZone数据 TODO 暂时不需要
// DealMainServerData.checkUpdateOtherMainServerZone();
UtilLog.COMMON_LOG.info("...第" + i + "组结束");
}
}
//刷新配置服的数据源等配置信息
Utils.refreshConfig();

UtilLog.COMMON_LOG.info("###操作结束!");
System.out.println("###操作结束!");

long endTime = System.currentTimeMillis();
long time = endTime - startTime;
UtilLog.COMMON_LOG.info("总时间:" + time / 1000 + "秒");

System.out.println("ok!");
}


}

 

#################################################

package com.game2sky;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.ibatis.session.SqlSession;

import com.game2sky.dao.BenfuDao;
import com.game2sky.deal.DealBenfuData;
import com.game2sky.deal.DeleteRepeatedId;
import com.game2sky.deal.VerifyMysql;
import com.game2sky.util.SqlSessionFactoryJava;
import com.game2sky.util.UtilLog;
import com.game2sky.util.Utils;

/**
*
* @author limengnan
*
*/
public class Delete {


public static List<String> allTableNames = null;
public static Map<String,String> tablePriKey = null;

public static void main(String[] args) {
CheckBoot.boot(Delete.class, args);
long startTime = System.currentTimeMillis();

List<String> executeLinuxCmd = null;
try {
executeLinuxCmd = CheckServerState.executeLinuxCmd("ps -ef|grep java");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (String s : executeLinuxCmd) {
if(s.contains("benfu")){
UtilLog.COMMON_LOG.info("###本服没有停服,程序终止!");
System.out.println("###本服没有停服,程序终止!");
// return;
}
}
if (Config.fromToServerIdMapList.size() > 0) {
for (int i = 0; i < Config.fromToServerIdMapList.size(); i++) {
UtilLog.COMMON_LOG.info("...第" + i + "组开始");
Config.fromToServerIdMap = Config.fromToServerIdMapList.get(i);
UtilLog.COMMON_LOG.info("...fromToServerIdMap:" + Config.fromToServerIdMap );
//删除被合服的服务器的相同的活动数据和配置数据
DealBenfuData.deleteBenfuData();
DealBenfuData.creatBenfuData();
// TODO 处理redis数据
// DealRedis.dealRedis();
//TODO
VerifyMysql.verifyMysql(false);
}
}


// List<Integer> keyList = mapT.entrySet().iterator().next().getKey();
// SqlSession sqlSession = Config.dbSessionMap.get(keyList.get(0));
// BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);
// allTableNames = benfuDao.selectTableNames();
//
// tablePriKey = new HashMap<>();
// for (String table : allTableNames) {
// tablePriKey.put(table, benfuDao.selectPriKey(table));
// System.out.println("没卡住 在执行中。。。。");
// }
//
// List<String> deleteTable = Utils.getFileContent("deleteTable.txt");
// List<String> notDeleteTable = Utils.getFileContent("deleteTableNot.txt");
//
// for (String s : deleteTable) {
// if(notDeleteTable.contains(s)){
// System.out.println("exit deleteTable error:"+s);
// UtilLog.COMMON_LOG.info("exit deleteTable error:"+s);
// System.exit(1);
// }
// }
// checkTableAndCreateTable(deleteTable, notDeleteTable);
// //处理redis数据
// DealRedis.dealRedis();


//删除数据库交错的表数据 TODO 目前看没有这种情况的发生 之后在确认
// deleteCrossDBTable("inst_formation");
// deleteCrossDBTable("inst_yyb_reward_record");
// //检查没有删除也没有去重的表是否有重复数据
// checkRepeatedTable(deleteTable);

System.out.println("ok!");
UtilLog.COMMON_LOG.info("ok!");

}

private static void checkIntenaServerGroup(){
SqlSession dictSession = null;
if(Utils.isTest){
dictSession = SqlSessionFactoryJava.openSessionByJava("com.mysql.jdbc.Driver",
"jdbc:mysql://172.16.1.51:3306/dict?useUnicode=true&amp;characterEncoding=UTF-8&amp;autoReconnect=true",
"root", "",false);
}else{
dictSession = SqlSessionFactoryJava.openSessionByJava("com.mysql.jdbc.Driver",
"jdbc:mysql://10.104.194.66:3306/dict?useUnicode=true&amp;characterEncoding=UTF-8&amp;autoReconnect=true",
"root", "1q2w3e4r1234@",false);
}

BenfuDao benfuDao = dictSession.getMapper(BenfuDao.class);
List<String> integServerGroup = benfuDao.getServerGroup("dict_integral_server");
List<String> seaFightServerGroup = benfuDao.getServerGroup("dict_union_seafight_servergroup");

HashMap<Integer, Integer> integServerMap = getIntegServerMap(integServerGroup);
HashMap<Integer, Integer> seaFightServerMap = getSeaFightServerMap(seaFightServerGroup);

Iterator<Map<List<Integer>, Integer>> iterator = Config.fromToServerIdMapList.iterator();
while(iterator.hasNext()){
Map<List<Integer>, Integer> next = iterator.next();
List<Integer> list = new ArrayList<>();
list.addAll(next.entrySet().iterator().next().getKey());
list.add(next.entrySet().iterator().next().getValue());

Set<Integer> groupSet = new HashSet<>();
for (int i : list) {
Integer integer = integServerMap.get(i);

groupSet.add(integer);
if(groupSet.size() > 1 ){
System.out.println("exit check 天梯 跨分组 error" + next);
UtilLog.COMMON_LOG.info("exit check 天梯 跨分组 error" + next);
UtilLog.LOG_ERROR.info("exit check 天梯 跨分组 error" + next);
System.exit(1);
}
}

groupSet.clear();
for (int i : list) {
Integer integer = seaFightServerMap.get(i);

groupSet.add(integer);
if(groupSet.size() > 1 ){
System.out.println("exit check 海战 跨分组 error"+next);
UtilLog.COMMON_LOG.info("exit check 海战 跨分组 error"+next);
UtilLog.LOG_ERROR.info("exit check 海战 跨分组 error"+next);
System.exit(1);
}
}
}
}

private static HashMap<Integer,Integer> getIntegServerMap(List<String> list){
int k = 0;
HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
for (String s : list) {
String[] split = s.split("-");
if(split.length > 1){
int min = Integer.parseInt(split[0]);
int max = Integer.parseInt(split[1]);
for (int i = min; i <= max; i++) {
map.put(i, k);
}
}else{
map.put(Integer.parseInt(split[0]), k);
}
k++;
}
return map;
}

private static HashMap<Integer,Integer> getSeaFightServerMap(List<String> list){
int k = 0;
HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
for (String s : list) {
List<String> asList = Arrays.asList(s.split(","));
for (String s1 : asList) {
String[] split = s1.split("-");
if(split.length > 1){
int min = Integer.parseInt(split[0]);
int max = Integer.parseInt(split[1]);
for (int i = min; i <= max; i++) {
map.put(i, k);
}
}else{
map.put(Integer.parseInt(split[0]), k);
}
}
k++;
}
return map;
}


private static void checkTableAndCreateTable(List<String> deleteTable,List<String> notDeleteTable){

for (Map<List<Integer>, Integer> map : Config.fromToServerIdMapList) {
List<String> needAddTables = new ArrayList<>();
for (Integer fromSid : map.entrySet().iterator().next().getKey()) {
SqlSession sqlSession = Config.dbSessionMap.get(fromSid);
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);
List<String> allTableNames = benfuDao.selectTableNames();
List<String> checkTableName = checkTableName(deleteTable, notDeleteTable,allTableNames);
if(checkTableName.size() > 0){
needAddTables.addAll(checkTableName);
}
}

System.out.println("add tables:"+needAddTables);
UtilLog.COMMON_LOG.info("add tables:"+needAddTables);
Integer toSid = map.entrySet().iterator().next().getValue();
SqlSession sqlSession = Config.dbSessionMap.get(toSid);
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);
for (String tableName:needAddTables) {
benfuDao.createTable(tableName);
}

}

}
public static void checkRepeatedTable(List<String> deleteTable) {
boolean isSuccess = true;
List<String> tableNames = new ArrayList<>(allTableNames);

tableNames.removeAll(deleteTable);
for (String s : DeleteRepeatedId.repeatedKeys) {
tableNames.remove(s.split(",")[0]);
}
tableNames.remove("inst_award_player");
tableNames.remove("inst_common_fight_data");
tableNames.remove("inst_union_apply");


for (String table : tableNames) {
//因为inst_arena_server_*表是每个单服独有的,其他服没有对应的表,因此不需要检查重复的数据
if(table.startsWith("inst_arena_server_")){
continue;
}
UtilLog.COMMON_LOG.info("begin checkRepeatedTable "+ table+"...");
if (Config.fromToServerIdMapList.size() > 0) {
for (int i = 0; i < Config.fromToServerIdMapList.size(); i++) {
Map<List<Integer>, Integer> map = Config.fromToServerIdMapList.get(i);
Entry<List<Integer>, Integer> next = map.entrySet().iterator().next();

String priKey = tablePriKey.get(table);

SqlSession sqlSession = Config.dbSessionMap.get(next.getValue());
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);
HashSet<Long> idset = null;
try {
idset = new HashSet<Long>(benfuDao.findFightId(priKey, table));
} catch (Exception e) {
UtilLog.COMMON_LOG.info("... continue "+table +", cannot convert to long");
System.out.println("... continue "+table +", cannot convert to long");
continue;
}

for (int j : next.getKey()) {
SqlSession sql = Config.dbSessionMap.get(j);
BenfuDao benfu = sql.getMapper(BenfuDao.class);
List<Long> idL = benfu.findFightId(priKey, table);
for (long l : idL) {
if(!idset.add(l)){
isSuccess = false;
UtilLog.COMMON_LOG.info("... error checkRepeatedTable contains "+table +",cursid:"+j+",currid:"+l);
UtilLog.LOG_ERROR.info("... error checkRepeatedTable contains "+table +",cursid:"+j+",currid:"+l);
System.out.println("... error checkRepeatedTable contains "+table +",cursid:"+j+",currid:"+l);
}
}
}
}
}
}

if(!isSuccess){
System.out.println("exit checkRepeatedTable error");
UtilLog.COMMON_LOG.info("exit checkRepeatedTable error");
UtilLog.LOG_ERROR.info("exit checkRepeatedTable error");
System.exit(1);
}

}
public static void checkLogicConfig() {
UtilLog.COMMON_LOG.info("begin checkLogicConfig...");
if (Config.fromToServerIdMapList.size() > 0) {
for (int i = 0; i < Config.fromToServerIdMapList.size(); i++) {
Map<List<Integer>, Integer> map = Config.fromToServerIdMapList.get(i);
Entry<List<Integer>, Integer> next = map.entrySet().iterator().next();
List<Integer> key = new ArrayList<Integer>(next.getKey());
key.add(next.getValue());
HashSet<Integer> set = new HashSet<Integer>();
for (int j : key) {
int zoneId = Config.zoneMap.get(j).getZoneId();
boolean add = set.add(zoneId);
if(!add){
System.out.println("exit checkLogicConfig error");
UtilLog.COMMON_LOG.info("exit checkLogicConfig error");
UtilLog.LOG_ERROR.info("exit checkLogicConfig error");
System.exit(1);
}
}
}
}
}

public static void deleteCrossDBTable(String tableName) {
UtilLog.COMMON_LOG.info("begin deleteCrossDBTable...");
if (Config.fromToServerIdMapList.size() > 0) {
for (int i = 0; i < Config.fromToServerIdMapList.size(); i++) {
Map<List<Integer>, Integer> map = Config.fromToServerIdMapList.get(i);
Entry<List<Integer>, Integer> next = map.entrySet().iterator().next();
List<Integer> key = new ArrayList<Integer>(next.getKey());
key.add(next.getValue());
for (int j : key) {
SqlSession sqlSession = Config.dbSessionMap.get(j);
BenfuDao benfuDao = sqlSession.getMapper(BenfuDao.class);
List<Long> selectOtherServerData = benfuDao.selectOtherServerData(tableName);

if(selectOtherServerData.size() > 0){
benfuDao.deleteRepeatedId(tableName, "playerId", selectOtherServerData);
sqlSession.commit();

UtilLog.LOG_ERROR.info("...delete :"+tableName+",currserver:"+j+",other server playerId:"+selectOtherServerData);
UtilLog.COMMON_LOG.info("...delete :"+tableName+",currserver:"+j+",other server playerId:"+selectOtherServerData);
}
}
}
}
}

public static List<String> checkTableName(List<String> deleteTable,List<String> notDeleteTable,List<String> allTables) {
List<String> tableNames = new ArrayList<>(allTables);

tableNames.removeAll(deleteTable);
tableNames.removeAll(notDeleteTable);

List<String> inst_arena_serverTableList = new ArrayList<>();
//这里是把inst_arena_server所对应的表删掉,因为在配置表中没法加,因此不考虑这些表了
if(tableNames.size() > 0){
Iterator<String> iterator = tableNames.iterator();
while(iterator.hasNext()){
String next = iterator.next();
if(next.startsWith("inst_arena_server_")){
inst_arena_serverTableList.add(next);
iterator.remove();
}
}
}

if(tableNames.size() > 0){
System.out.println("exit checkTableName error1:"+tableNames);
UtilLog.COMMON_LOG.info("exit checkTableName error1:"+tableNames);
UtilLog.LOG_ERROR.info("exit checkTableName error1:"+tableNames);
System.exit(1);
}

return inst_arena_serverTableList;
}



}

##############################################

resources package

application.properties    -----   spring.profiles.active=gw

 

application-and.properties----------------------

#banner.location=classpath:yckj.txt

mybatis.cfg.xml=mybatis-config-main-and.xml
fromToServerId=and_fromToServerId
url.config.properties=url-config-and.properties
conf.properties=conf.properties
ip=172.16.1.162
port=12307

 

---------------------------------

#要从哪考数据,可以是多个服,用于替换{0}表示的serverId以及获取redis数据源
#要考到哪里去,用于获取该服对应的redis数据源,ip是执行进程的机器内网ip,该机器只执行对应ip下的服 类似: fromToServerId=193.112.92.50:1186-1187,1189>1181;193.112.102.94:6-17,28>5
#如果一台服务器上有两组要逻辑合服的情况,直接写两组ip相同的就行,如:10.104.181.207:1051>1041;10.104.181.207:1071>1061
and_fromToServerId=10.104.166.125:1021>1002;10.104.181.207:1061>1041;10.104.175.36:1101>1081;10.104.231.83:1141>1121;10.104.211.86:2011>2002;10.104.43.195:2051>2041;10.104.13.124:2262-2270>2261;10.104.13.124:2272-2280>2271;10.104.19.240:2282-2290>2281;10.104.38.45:2302-2310>2301;10.104.2.99:2322-2330>2321
gw_fromToServerId=10.1.17.54:3002-3010>3001
yh_fromToServerId=10.104.217.4:3021>3002;10.104.25.196:3101>3081
ios_fromToServerId=10.104.16.144:7101>7081;10.104.165.13:7141>7121;10.104.8.190:7181>7161;10.104.18.91:7261>7241;10.104.143.184:7291>7281;10.104.143.184:7311>7301;10.104.250.75:6022-6031>6021;10.104.136.99:6082-6090>6081;10.104.136.99:6111>6101;10.104.55.230:6131>6121;10.104.53.18:6203-6210>6202;10.104.29.68:6242-6250>6241;10.104.29.68:6252-6260>6251;10.104.29.68:6262-6270>6261;10.104.29.68:6272-6280>6271;10.104.65.150:6282-6290>6281
test_fromToServerId=172.16.2.138:96>97
prod_fromToServerId=10.1.21.89:3002>3001
xf_fromToServerId=
9997_fromToServerId=
#test_fromToServerId=172.16.1.81:1187-1188>1186
#平台id,安卓:1,官网:2,硬核:3,ios:4

#check完成之后需要看error日志,如果有重复的数据会打印出来,需要手动处理删除
#check完成之后需要看error日志,如果有重复的数据会打印出来,需要手动处理删除
#check完成之后需要看error日志,如果有重复的数据会打印出来,需要手动处理删除
#check完成之后需要看error日志,如果有重复的数据会打印出来,需要手动处理删除
#check完成之后需要看error日志,如果有重复的数据会打印出来,需要手动处理删除
#check完成之后需要看error日志,如果有重复的数据会打印出来,需要手动处理删除
#check完成之后需要看error日志,如果有重复的数据会打印出来,需要手动处理删除

-----------------------------------------------

#这些表需要加上服务器id新建
inst_player_blood_palace

 ------------------------------------------------

 

log4j.properties-----

### set log levels ###
log4j.rootLogger=INFO,stdout,commonLogger

### 输出到控制台 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d %5p [%t] (%F\\:%L) - %m%n
log4j.appender.stdout.encoding = UTF-8

### 普通日志 ###
log4j.appender.commonLogger = org.apache.log4j.DailyRollingFileAppender
log4j.appender.commonLogger.File = logs/common/common.log
log4j.appender.commonLogger.DatePattern = '.'yyyy.MM.dd
log4j.appender.commonLogger.Append = true
log4j.appender.commonLogger.layout = org.apache.log4j.PatternLayout
log4j.appender.commonLogger.layout.ConversionPattern = %d %5p [%t] (%F\:%L) - %m%n
log4j.appender.commonLogger.encoding = UTF-8
log4j.additivity.commonLogger = false
log4j.logger.commonLogger = INFO,stdout

### 异常日志 ###
log4j.appender.errorLogger = org.apache.log4j.DailyRollingFileAppender
log4j.appender.errorLogger.File = logs/error/error.log
log4j.appender.errorLogger.DatePattern = '.'yyyy.MM.dd
log4j.appender.errorLogger.Append = true
log4j.appender.errorLogger.layout = org.apache.log4j.PatternLayout
log4j.appender.errorLogger.layout.ConversionPattern = %d %5p [%t] (%F\:%L) - %m%n
log4j.appender.errorLogger.encoding=UTF-8
log4j.additivity.errorLogger = false
log4j.logger.errorLogger = INFO,stdout

 

------------------------------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level (%F\:%L) - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="info" additivity="false" includeLocation="true">
<AppenderRef ref="Console" />
</Root>

<!-- 打印hibernate的info日志 -->
<Logger name="org.hibernate" level="error" additivity="false">
<AppenderRef ref="Console" />
</Logger>

</Loggers>
</Configuration>

-----------------------------------------------------------

 

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 别名定义 推荐这种方式 扫描该包中的实体类以及子包中的实体类-->
<typeAliases>
<package name="com.game2sky.mmo.tools.logicmerge.domain"/>
</typeAliases>

<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://10.66.118.186:3306/main_server?useUnicode=true&amp;characterEncoding=UTF-8&amp;autoReconnect=true" />
<property name="username" value="root" />
<property name="password" value="guiqi@YCYX" />
</dataSource>
</environment>
</environments>

<mappers>
<mapper class="com.game2sky.dao.ConfigServerZoneDao"/>
<mapper class="com.game2sky.dao.DataSourceConfigDao"/>
<mapper class="com.game2sky.dao.DataSourceRedisConfigDao"/>
<mapper class="com.game2sky.dao.ProcessBenfuConfigDao"/>
<mapper class="com.game2sky.dao.BenfuDao"/>
<mapper class="com.game2sky.dao.MainServerDao"/>
<mapper class="com.game2sky.dao.ProcessDBSConfigDao"/>
<mapper class="com.game2sky.dao.DataSourceDictConfigDao"/>
</mappers>

</configuration>

 ***************************************************************************

start.sh  -----------------------   

java -Xmx1024M -Xms1024M -Xss256k -Xmn512M -classpath mmo.toolsmerge.jar  com.game2sky.DealMain --resource=`pwd`/resource --spring.profiles.active=$1

posted @ 2021-09-09 11:13  小堆堆儿  阅读(99)  评论(0编辑  收藏  举报