Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue 28 #87

Merged
merged 6 commits into from
Apr 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ private void startClient(CIMServerResVO.ServerInfo cimServer) {
LOGGER.error("连接失败", e);
}
if (future.isSuccess()) {
echoService.echo("start cim client success!");
echoService.echo("Start cim client success!");
LOGGER.info("启动 cim client 成功");
}
channel = (SocketChannel) future.channel();
Expand Down Expand Up @@ -158,7 +158,7 @@ private void loginCIMServer() {
.build();
ChannelFuture future = channel.writeAndFlush(login);
future.addListener((ChannelFutureListener) channelFuture ->
echoService.echo("registry cim server success!")
echoService.echo("Registry cim server success!")
);
}

Expand Down
4 changes: 2 additions & 2 deletions cim-client/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ swagger.enable = true

logging.level.root=error

#消息记录存放路径
# 消息记录存放路径
cim.msg.logger.path = /opt/logs/cim/


Expand Down Expand Up @@ -45,7 +45,7 @@ cim.server.online.user.url=http://localhost:8083/onlineUser
cim.clear.route.request.url=http://localhost:8083/offLine

# 客户端唯一ID
cim.user.id=1566914867344
cim.user.id=1586617710861
cim.user.userName=zhangsan

# 回调线程队列大小
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,26 @@ public enum StatusEnum {
/** 成功 */
FALLBACK("8000", "FALL_BACK"),
/** 参数校验失败**/
VALIDATION_FAIL("3000", "参数校验失败"),
VALIDATION_FAIL("3000", "invalid argument"),
/** 失败 */
FAIL("4000", "失败"),

/** 重复登录 */
REPEAT_LOGIN("5000", "账号重复登录,请退出一个账号!"),
REPEAT_LOGIN("5000", "Repeat login, log out an account please!"),

/** 请求限流 */
REQUEST_LIMIT("6000", "请求限流"),

/** 账号不在线 */
OFF_LINE("7000", "你选择的账号不在线,请重新选择!"),

SERVER_NOT_AVAILABLE("7100", "CIM server is not available, please try again later!"),

/** 登录信息不匹配 */
ACCOUNT_NOT_MATCH("9100", "登录信息不匹配!"),
ACCOUNT_NOT_MATCH("9100", "The User information you have used is incorrect!"),



/** 请求限流 */
REQUEST_LIMIT("6000", "请求限流"),
;


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.crossoverjie.cim.common.pojo;

/**
* Function:
*
* @author crossoverJie
* Date: 2020-04-12 20:48
* @since JDK 1.8
*/
public final class RouteInfo {

private String ip ;
private Integer cimServerPort;
private Integer httpPort;

public RouteInfo(String ip, Integer cimServerPort, Integer httpPort) {
this.ip = ip;
this.cimServerPort = cimServerPort;
this.httpPort = httpPort;
}

public String getIp() {
return ip;
}

public void setIp(String ip) {
this.ip = ip;
}

public Integer getCimServerPort() {
return cimServerPort;
}

public void setCimServerPort(Integer cimServerPort) {
this.cimServerPort = cimServerPort;
}

public Integer getHttpPort() {
return httpPort;
}

public void setHttpPort(Integer httpPort) {
this.httpPort = httpPort;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.crossoverjie.cim.common.route.algorithm.consistenthash;

import com.crossoverjie.cim.common.enums.StatusEnum;
import com.crossoverjie.cim.common.exception.CIMException;

import java.util.SortedMap;
import java.util.TreeMap;

Expand Down Expand Up @@ -35,6 +38,9 @@ public String getFirstNodeValue(String value) {
if (!last.isEmpty()) {
return last.get(last.firstKey());
}
if (treeMap.size() == 0){
throw new CIMException(StatusEnum.SERVER_NOT_AVAILABLE) ;
}
return treeMap.firstEntry().getValue();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.crossoverjie.cim.common.util;

import com.crossoverjie.cim.common.exception.CIMException;
import com.crossoverjie.cim.common.pojo.RouteInfo;

import static com.crossoverjie.cim.common.enums.StatusEnum.VALIDATION_FAIL;

/**
* Function:
*
* @author crossoverJie
* Date: 2020-04-12 20:42
* @since JDK 1.8
*/
public class RouteInfoParseUtil {

public static RouteInfo parse(String info){
try {
String[] serverInfo = info.split(":");
RouteInfo routeInfo = new RouteInfo(serverInfo[0], Integer.parseInt(serverInfo[1]),Integer.parseInt(serverInfo[2])) ;
return routeInfo ;
}catch (Exception e){
throw new CIMException(VALIDATION_FAIL) ;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class RouteApplication implements CommandLineRunner{

public static void main(String[] args) {
SpringApplication.run(RouteApplication.class, args);
LOGGER.info("启动 route 成功");
LOGGER.info("Start cim route success!!!");
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
import com.crossoverjie.cim.common.enums.StatusEnum;
import com.crossoverjie.cim.common.exception.CIMException;
import com.crossoverjie.cim.common.pojo.CIMUserInfo;
import com.crossoverjie.cim.common.pojo.RouteInfo;
import com.crossoverjie.cim.common.res.BaseResponse;
import com.crossoverjie.cim.common.res.NULLBody;
import com.crossoverjie.cim.common.route.algorithm.RouteHandle;
import com.crossoverjie.cim.common.util.RouteInfoParseUtil;
import com.crossoverjie.cim.route.cache.ServerCache;
import com.crossoverjie.cim.route.service.AccountService;
import com.crossoverjie.cim.route.service.CommonBizService;
import com.crossoverjie.cim.route.service.UserInfoCacheService;
import com.crossoverjie.cim.route.vo.req.ChatReqVO;
import com.crossoverjie.cim.route.vo.req.LoginReqVO;
Expand Down Expand Up @@ -49,6 +52,8 @@ public class RouteController {
@Autowired
private UserInfoCacheService userInfoCacheService ;

@Autowired
private CommonBizService commonBizService ;

@Autowired
private RouteHandle routeHandle ;
Expand Down Expand Up @@ -128,7 +133,7 @@ public BaseResponse<NULLBody> offLine(@RequestBody ChatReqVO groupReqVO) throws

CIMUserInfo cimUserInfo = userInfoCacheService.loadUserInfoByUserId(groupReqVO.getUserId());

LOGGER.info("下线用户[{}]", cimUserInfo.toString());
LOGGER.info("user [{}] offline!", cimUserInfo.toString());
accountService.offLine(groupReqVO.getUserId());

res.setCode(StatusEnum.SUCCESS.getCode());
Expand All @@ -147,17 +152,19 @@ public BaseResponse<NULLBody> offLine(@RequestBody ChatReqVO groupReqVO) throws
public BaseResponse<CIMServerResVO> login(@RequestBody LoginReqVO loginReqVO) throws Exception {
BaseResponse<CIMServerResVO> res = new BaseResponse();

// check server available
String server = routeHandle.routeServer(serverCache.getAll(),String.valueOf(loginReqVO.getUserId()));
RouteInfo routeInfo = RouteInfoParseUtil.parse(server);
commonBizService.checkServerAvailable(routeInfo);

//登录校验
StatusEnum status = accountService.login(loginReqVO);
if (status == StatusEnum.SUCCESS) {

String server = routeHandle.routeServer(serverCache.getAll(),String.valueOf(loginReqVO.getUserId()));
String[] serverInfo = server.split(":");
CIMServerResVO vo = new CIMServerResVO(serverInfo[0], Integer.parseInt(serverInfo[1]),Integer.parseInt(serverInfo[2]));

//保存路由信息
accountService.saveRouteInfo(loginReqVO,server);

CIMServerResVO vo = new CIMServerResVO(routeInfo);
res.setDataBody(vo);

}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.crossoverjie.cim.route.exception;

import com.crossoverjie.cim.common.exception.CIMException;
import com.crossoverjie.cim.common.res.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
* Function:
*
* @author crossoverJie
* Date: 2020-04-12 22:13
* @since JDK 1.8
*/
@ControllerAdvice
public class ExceptionHandlingController {

private static Logger logger = LoggerFactory.getLogger(ExceptionHandlingController.class) ;

@ExceptionHandler(CIMException.class)
@ResponseBody()
public BaseResponse handleAllExceptions(CIMException ex) {
logger.error("exception", ex);
BaseResponse baseResponse = new BaseResponse();
baseResponse.setCode(ex.getErrorCode());
baseResponse.setMessage(ex.getMessage());
return baseResponse ;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.crossoverjie.cim.route.kit;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
* Function:
*
* @author crossoverJie
* Date: 2020-04-12 20:32
* @since JDK 1.8
*/
public class NetAddressIsReachable {

/**
* check ip and port
*
* @param address
* @param port
* @param timeout
* @return True if connection successful
*/
public static boolean checkAddressReachable(String address, int port, int timeout) {
Socket socket = new Socket() ;
try {
socket.connect(new InetSocketAddress(address, port), timeout);
return true;
} catch (IOException exception) {
return false;
} finally {
try {
socket.close();
} catch (IOException e) {
return false ;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public void subscribeEvent(String path) {
zkClient.subscribeChildChanges(path, new IZkChildListener() {
@Override
public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
logger.info("清除/更新本地缓存 parentPath=【{}】,currentChilds=【{}】", parentPath,currentChilds.toString());
logger.info("Clear or update local cache parentPath=[{}],currentChilds=[{}]", parentPath,currentChilds.toString());

//更新所有缓存/先删除 再新增
serverCache.updateCache(currentChilds) ;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.crossoverjie.cim.route.service;

import com.crossoverjie.cim.common.enums.StatusEnum;
import com.crossoverjie.cim.common.exception.CIMException;
import com.crossoverjie.cim.common.pojo.RouteInfo;
import com.crossoverjie.cim.route.kit.NetAddressIsReachable;
import org.springframework.stereotype.Component;

/**
* Function:
*
* @author crossoverJie
* Date: 2020-04-12 21:40
* @since JDK 1.8
*/
@Component
public class CommonBizService {

/**
* check ip and port
* @param routeInfo
*/
public void checkServerAvailable(RouteInfo routeInfo){
boolean reachable = NetAddressIsReachable.checkAddressReachable(routeInfo.getIp(), routeInfo.getCimServerPort(), 1000);
if (!reachable) {
throw new CIMException(StatusEnum.SERVER_NOT_AVAILABLE) ;
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ public interface UserInfoCacheService {


/**
*
* @return 获取所有在线用户
* query all online user
* @return online user
*/
Set<CIMUserInfo> onlineUser() ;
}
Loading