Commit 5e13875d by liyuan

修改

parent 74f3a090
...@@ -181,7 +181,7 @@ public class RegistryBaseClient { ...@@ -181,7 +181,7 @@ public class RegistryBaseClient {
registryParamVO.setAccessToken(this.accessToken); registryParamVO.setAccessToken(this.accessToken);
registryParamVO.setBiz(this.biz); registryParamVO.setBiz(this.biz);
registryParamVO.setEnv(this.env); registryParamVO.setEnv(this.env);
registryParamVO.setKeys(new ArrayList<String>(keys)); registryParamVO.setKeys(new ArrayList<>(keys));
String paramsJson = BasicJson.toJson(registryParamVO); String paramsJson = BasicJson.toJson(registryParamVO);
......
...@@ -259,14 +259,14 @@ public class RegistryServiceImpl implements IRegistryService, InitializingBean, ...@@ -259,14 +259,14 @@ public class RegistryServiceImpl implements IRegistryService, InitializingBean,
} }
} }
Map<String, List<String>> result = new HashMap<String, List<String>>(); Map<String, List<String>> result = new HashMap<>(16);
for (String key: keys) { for (String key: keys) {
RegistryData registryData = new RegistryData(); RegistryData registryData = new RegistryData();
registryData.setBiz(biz); registryData.setBiz(biz);
registryData.setEnv(env); registryData.setEnv(env);
registryData.setKey(key); registryData.setKey(key);
List<String> dataList = new ArrayList<String>(); List<String> dataList = new ArrayList<>();
Registry fileRegistry = getFileRegistryData(registryData); Registry fileRegistry = getFileRegistryData(registryData);
if (fileRegistry!=null) { if (fileRegistry!=null) {
dataList = fileRegistry.getDataList(); dataList = fileRegistry.getDataList();
...@@ -482,7 +482,7 @@ public class RegistryServiceImpl implements IRegistryService, InitializingBean, ...@@ -482,7 +482,7 @@ public class RegistryServiceImpl implements IRegistryService, InitializingBean,
public void run() { public void run() {
while (!executorStoped) { while (!executorStoped) {
try { try {
// new message, filter readed // new message, filters readed
List<RegistryMessage> messageList = registryMessageDao.findMessage(readedMessageIds); List<RegistryMessage> messageList = registryMessageDao.findMessage(readedMessageIds);
if (messageList!=null && messageList.size()>0) { if (messageList!=null && messageList.size()>0) {
for (RegistryMessage message: messageList) { for (RegistryMessage message: messageList) {
......
### web ### web
server.port=8080 server.port=8080
server.context-path=/myth-register server.context-path=/myth-register
logging.config=classpath:logback.xml
### resources ### resources
spring.mvc.static-path-pattern=/static/** spring.mvc.static-path-pattern=/static/**
......
...@@ -30,11 +30,11 @@ public abstract class ServiceRegistry { ...@@ -30,11 +30,11 @@ public abstract class ServiceRegistry {
/** /**
* registry service, for mult * registry service, for mult
* *
* @param keys service key * @param keyServerAddress Map's key is service key Map'svalue is service value/ip:port
* @param value service value/ip:port
* @return
*/ */
public abstract boolean registry(Set<String> keys, String value);
public abstract boolean registry(Map<String,String> keyServerAddress);
/** /**
......
package com.byit.rpc.registry.impl; package com.byit.rpc.registry.impl;
import com.byit.registry.client.model.RegistryDataParamVO;
import com.byit.rpc.registry.ServiceRegistry; import com.byit.rpc.registry.ServiceRegistry;
import org.springframework.util.CollectionUtils;
import java.util.HashMap; import java.util.*;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/** /**
* service registry for "local" * service registry for "local"
...@@ -33,20 +32,22 @@ public class LocalServiceRegistry extends ServiceRegistry { ...@@ -33,20 +32,22 @@ public class LocalServiceRegistry extends ServiceRegistry {
registryData.clear(); registryData.clear();
} }
@Override @Override
public boolean registry(Set<String> keys, String value) { public boolean registry(Map<String,String> keyServerAddress){
if (keys==null || keys.size()==0 || value==null || value.trim().length()==0) { if (CollectionUtils.isEmpty(keyServerAddress)) {
return false; return false;
} }
for (String key : keys) {
TreeSet<String> values = registryData.get(key); // init
for (Map.Entry<String,String> entry : keyServerAddress.entrySet()) {
TreeSet<String> values = registryData.get(entry.getKey());
if (values == null) { if (values == null) {
values = new TreeSet<>(); values = new TreeSet<>();
registryData.put(key, values); registryData.put(entry.getKey(), values);
} }
values.add(value); values.add(entry.getValue());
} }
return true; return true;
} }
......
...@@ -3,6 +3,7 @@ package com.byit.rpc.registry.impl; ...@@ -3,6 +3,7 @@ package com.byit.rpc.registry.impl;
import com.byit.registry.client.RegistryClient; import com.byit.registry.client.RegistryClient;
import com.byit.registry.client.model.RegistryDataParamVO; import com.byit.registry.client.model.RegistryDataParamVO;
import com.byit.rpc.registry.ServiceRegistry; import com.byit.rpc.registry.ServiceRegistry;
import org.springframework.util.CollectionUtils;
import java.util.*; import java.util.*;
...@@ -43,16 +44,17 @@ public class RegistryServiceRegistry extends ServiceRegistry { ...@@ -43,16 +44,17 @@ public class RegistryServiceRegistry extends ServiceRegistry {
} }
} }
@Override @Override
public boolean registry(Set<String> keys, String value) { public boolean registry(Map<String,String> keyServerAddress){
if (keys==null || keys.size() == 0 || value == null) { if (CollectionUtils.isEmpty(keyServerAddress)) {
return false; return false;
} }
// init // init
List<RegistryDataParamVO> registryDataList = new ArrayList<>(); List<RegistryDataParamVO> registryDataList = new ArrayList<>();
for (String key:keys) { for (Map.Entry<String,String> entry : keyServerAddress.entrySet()) {
registryDataList.add(new RegistryDataParamVO(key, value)); registryDataList.add(new RegistryDataParamVO(entry.getKey(), entry.getValue()));
} }
return registryClient.registry(registryDataList); return registryClient.registry(registryDataList);
......
package com.byit.rpc.registry.impl; package com.byit.rpc.registry.impl;
import com.byit.registry.client.model.RegistryDataParamVO;
import com.byit.rpc.registry.ServiceRegistry; import com.byit.rpc.registry.ServiceRegistry;
import com.byit.rpc.util.RpcException; import com.byit.rpc.util.RpcException;
import com.byit.rpc.util.ZkClient; import com.byit.rpc.util.ZkClient;
...@@ -7,6 +8,7 @@ import org.apache.zookeeper.WatchedEvent; ...@@ -7,6 +8,7 @@ import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
...@@ -232,25 +234,37 @@ public class ZkServiceRegistry extends ServiceRegistry { ...@@ -232,25 +234,37 @@ public class ZkServiceRegistry extends ServiceRegistry {
} }
} }
@Override @Override
public boolean registry(Set<String> keys, String value) { public boolean registry(Map<String,String> keyServerAddress){
for (String key : keys) { if (CollectionUtils.isEmpty(keyServerAddress)) {
return false;
}
StringBuilder keys = new StringBuilder();
StringBuilder addressValues = new StringBuilder();
// init
for (Map.Entry<String,String> entry : keyServerAddress.entrySet()) {
// local cache // local cache
TreeSet<String> values = registryData.get(key); TreeSet<String> values = registryData.get(entry.getKey());
if (values == null) { if (values == null) {
values = new TreeSet<>(); values = new TreeSet<>();
registryData.put(key, values); registryData.put(entry.getKey(), values);
} }
values.add(value); values.add(entry.getValue());
// make path, child path // make path, child path
String path = keyToPath(key); String path = keyToPath(entry.getKey());
zkClient.setChildPathData(path, value, ""); keys.append(entry.getKey() + ",");
addressValues.append(entry.getValue() + ",");
zkClient.setChildPathData(path, entry.getValue(), "");
} }
logger.info(">>>>>>>>>>> myth-rpc, registry success, keys = {}, value = {}", keys, value);
logger.info(">>>>>>>>>>> myth-rpc, registry success, keys = {}, value = {}", keys, addressValues);
return true; return true;
} }
@Override @Override
public boolean remove(Set<String> keys, String value) { public boolean remove(Set<String> keys, String value) {
for (String key : keys) { for (String key : keys) {
......
...@@ -147,7 +147,7 @@ public class RpcReferenceBean { ...@@ -147,7 +147,7 @@ public class RpcReferenceBean {
Class<?>[] parameterTypes = method.getParameterTypes(); Class<?>[] parameterTypes = method.getParameterTypes();
Object[] parameters = args; Object[] parameters = args;
// filter for generic // filters for generic
if (className.equals(RpcGenericService.class.getName()) && methodName.equals("invoke")) { if (className.equals(RpcGenericService.class.getName()) && methodName.equals("invoke")) {
Class<?>[] paramTypes = null; Class<?>[] paramTypes = null;
...@@ -168,7 +168,7 @@ public class RpcReferenceBean { ...@@ -168,7 +168,7 @@ public class RpcReferenceBean {
parameters = (Object[]) args[4]; parameters = (Object[]) args[4];
} }
// filter method like "Object.toString()" // filters method like "Object.toString()"
if (className.equals(Object.class.getName())) { if (className.equals(Object.class.getName())) {
logger.info(">>>>>>>>>>> myth-rpc proxy class-method not support [{}#{}]", className, methodName); logger.info(">>>>>>>>>>> myth-rpc proxy class-method not support [{}#{}]", className, methodName);
throw new RpcException("myth-rpc proxy class-method not support"); throw new RpcException("myth-rpc proxy class-method not support");
...@@ -187,7 +187,7 @@ public class RpcReferenceBean { ...@@ -187,7 +187,7 @@ public class RpcReferenceBean {
} else if (addressSet.size()==1) { } else if (addressSet.size()==1) {
finalAddress = addressSet.first(); finalAddress = addressSet.first();
} else { } else {
finalAddress = loadBalance.xxlRpcInvokerRouter.route(serviceKey, addressSet); finalAddress = loadBalance.rpcInvokerRouter.route(serviceKey, addressSet);
} }
} }
......
...@@ -11,10 +11,10 @@ public enum LoadBalance { ...@@ -11,10 +11,10 @@ public enum LoadBalance {
CONSISTENT_HASH(new RpcLoadBalanceConsistentHashStrategy()); CONSISTENT_HASH(new RpcLoadBalanceConsistentHashStrategy());
public final RpcLoadBalance xxlRpcInvokerRouter; public final RpcLoadBalance rpcInvokerRouter;
private LoadBalance(RpcLoadBalance xxlRpcInvokerRouter) { private LoadBalance(RpcLoadBalance rpcInvokerRouter) {
this.xxlRpcInvokerRouter = xxlRpcInvokerRouter; this.rpcInvokerRouter = rpcInvokerRouter;
} }
...@@ -26,6 +26,4 @@ public enum LoadBalance { ...@@ -26,6 +26,4 @@ public enum LoadBalance {
} }
return defaultRouter; return defaultRouter;
} }
} }
\ No newline at end of file
...@@ -26,7 +26,7 @@ public class MinaClientHandler extends IoHandlerAdapter { ...@@ -26,7 +26,7 @@ public class MinaClientHandler extends IoHandlerAdapter {
public void messageReceived(IoSession session, Object message) throws Exception { public void messageReceived(IoSession session, Object message) throws Exception {
RpcResponse xxlRpcResponse = (RpcResponse) message; RpcResponse xxlRpcResponse = (RpcResponse) message;
// filter beat // filters beat
if (Beat.BEAT_ID.equalsIgnoreCase(xxlRpcResponse.getRequestId())){ if (Beat.BEAT_ID.equalsIgnoreCase(xxlRpcResponse.getRequestId())){
return; return;
} }
......
...@@ -37,7 +37,7 @@ public class MinaServerHandler extends IoHandlerAdapter { ...@@ -37,7 +37,7 @@ public class MinaServerHandler extends IoHandlerAdapter {
// request // request
final RpcRequest rpcRequest = (RpcRequest) message; final RpcRequest rpcRequest = (RpcRequest) message;
// filter beat // filters beat
if (Beat.BEAT_ID.equalsIgnoreCase(rpcRequest.getRequestId())){ if (Beat.BEAT_ID.equalsIgnoreCase(rpcRequest.getRequestId())){
return; return;
} }
......
...@@ -33,7 +33,7 @@ public class NettyServerHandler extends SimpleChannelInboundHandler<RpcRequest> ...@@ -33,7 +33,7 @@ public class NettyServerHandler extends SimpleChannelInboundHandler<RpcRequest>
@Override @Override
public void channelRead0(final ChannelHandlerContext ctx, final RpcRequest rpcRequest) throws Exception { public void channelRead0(final ChannelHandlerContext ctx, final RpcRequest rpcRequest) throws Exception {
// filter beat // filters beat
if (Beat.BEAT_ID.equalsIgnoreCase(rpcRequest.getRequestId())){ if (Beat.BEAT_ID.equalsIgnoreCase(rpcRequest.getRequestId())){
logger.debug(">>>>>>>>>>> myth-rpc provider netty server read beat-ping."); logger.debug(">>>>>>>>>>> myth-rpc provider netty server read beat-ping.");
return; return;
......
...@@ -80,7 +80,7 @@ public class NettyHttpServerHandler extends SimpleChannelInboundHandler<FullHttp ...@@ -80,7 +80,7 @@ public class NettyHttpServerHandler extends SimpleChannelInboundHandler<FullHttp
RpcRequest rpcRequest = (RpcRequest) rpcProviderFactory.getSerializer().deserialize(requestBytes, RpcRequest.class); RpcRequest rpcRequest = (RpcRequest) rpcProviderFactory.getSerializer().deserialize(requestBytes, RpcRequest.class);
requestId = rpcRequest.getRequestId(); requestId = rpcRequest.getRequestId();
// filter beat // filters beat
if (Beat.BEAT_ID.equalsIgnoreCase(rpcRequest.getRequestId())){ if (Beat.BEAT_ID.equalsIgnoreCase(rpcRequest.getRequestId())){
logger.debug(">>>>>>>>>>> myth-rpc provider netty_http server read beat-ping."); logger.debug(">>>>>>>>>>> myth-rpc provider netty_http server read beat-ping.");
return; return;
......
...@@ -20,232 +20,257 @@ import java.util.Map; ...@@ -20,232 +20,257 @@ import java.util.Map;
/** /**
* provider * provider
*
*/ */
public class RpcProviderFactory { public class RpcProviderFactory {
private static final Logger logger = LoggerFactory.getLogger(RpcProviderFactory.class); private static final Logger logger = LoggerFactory.getLogger(RpcProviderFactory.class);
// ---------------------- config ---------------------- // ---------------------- config ----------------------
private NetEnum netType; private NetEnum netType;
private Serializer serializer; private Serializer serializer;
private int corePoolSize; private int corePoolSize;
private int maxPoolSize; private int maxPoolSize;
private String ip; // for registry private String ip; // for registry
private int port; // default port private int port; // default port
private String accessToken; private String accessToken;
private int serverPort;
private Class<? extends ServiceRegistry> serviceRegistryClass; private String serverName;
private Map<String, String> serviceRegistryParam; /**
* 该服务是否提供http服务
*/
public RpcProviderFactory() { private Boolean isHttp;
}
public void initConfig(NetEnum netType, private Class<? extends ServiceRegistry> serviceRegistryClass;
Serializer serializer, private Map<String, String> serviceRegistryParam;
int corePoolSize,
int maxPoolSize,
String ip, public RpcProviderFactory() {
int port, }
String accessToken,
Class<? extends ServiceRegistry> serviceRegistryClass, public void initConfig(NetEnum netType,
Map<String, String> serviceRegistryParam) { Serializer serializer,
int corePoolSize,
// init int maxPoolSize,
this.netType = netType; String ip,
this.serializer = serializer; int port,
this.corePoolSize = corePoolSize; boolean isHttp,
this.maxPoolSize = maxPoolSize; int serverPort,
this.ip = ip; String serverName,
this.port = port; String accessToken,
this.accessToken = accessToken; Class<? extends ServiceRegistry> serviceRegistryClass,
this.serviceRegistryClass = serviceRegistryClass; Map<String, String> serviceRegistryParam) {
this.serviceRegistryParam = serviceRegistryParam;
// init
// valid this.netType = netType;
if (this.netType==null) { this.serializer = serializer;
throw new RpcException("myth-rpc provider netType missing."); this.corePoolSize = corePoolSize;
} this.maxPoolSize = maxPoolSize;
if (this.serializer==null) { this.ip = ip;
throw new RpcException("myth-rpc provider serializer missing."); this.port = port;
} this.isHttp = isHttp;
if (!(this.corePoolSize>=0 && this.maxPoolSize>0 && this.maxPoolSize>=this.corePoolSize)) { this.serverPort = serverPort;
this.corePoolSize = 60; this.serverName = serverName;
this.maxPoolSize = 300; this.accessToken = accessToken;
} this.serviceRegistryClass = serviceRegistryClass;
if (this.ip == null) { this.serviceRegistryParam = serviceRegistryParam;
this.ip = IpUtil.getIp();
} // valid
if (this.port <= 0) { if (this.netType == null) {
this.port = 7080; throw new RpcException("myth-rpc provider netType missing.");
} }
if (NetUtil.isPortUsed(this.port)) { if (this.serializer == null) {
throw new RpcException("myth-rpc provider port["+ this.port +"] is used."); throw new RpcException("myth-rpc provider serializer missing.");
} }
if (this.serviceRegistryClass != null) { if (!(this.corePoolSize >= 0 && this.maxPoolSize > 0 && this.maxPoolSize >= this.corePoolSize)) {
if (this.serviceRegistryParam == null) { this.corePoolSize = 60;
throw new RpcException("myth-rpc provider serviceRegistryParam is missing."); this.maxPoolSize = 300;
} }
} if (this.ip == null) {
this.ip = IpUtil.getIp();
} }
if (this.port <= 0) {
public Serializer getSerializer() { this.port = 7080;
return serializer; }
} if (NetUtil.isPortUsed(this.port)) {
throw new RpcException("myth-rpc provider port[" + this.port + "] is used.");
public int getPort() { }
return port; if (this.serviceRegistryClass != null) {
} if (this.serviceRegistryParam == null) {
throw new RpcException("myth-rpc provider serviceRegistryParam is missing.");
public int getCorePoolSize() { }
return corePoolSize; }
}
}
public int getMaxPoolSize() {
return maxPoolSize; public Serializer getSerializer() {
} return serializer;
}
// ---------------------- start / stop ----------------------
public int getPort() {
private Server server; return port;
private ServiceRegistry serviceRegistry; }
private String serviceAddress;
public int getCorePoolSize() {
public void start() throws Exception { return corePoolSize;
// start server }
serviceAddress = IpUtil.getIpPort(this.ip, port);
server = netType.serverClass.newInstance(); public int getMaxPoolSize() {
server.setStartedCallback(new BaseCallback() { // serviceRegistry started return maxPoolSize;
@Override }
public void run() throws Exception {
// start registry // ---------------------- start / stop ----------------------
if (serviceRegistryClass != null) {
serviceRegistry = serviceRegistryClass.newInstance(); private Server server;
serviceRegistry.start(serviceRegistryParam); private ServiceRegistry serviceRegistry;
if (serviceData.size() > 0) { private String serviceAddress;
serviceRegistry.registry(serviceData.keySet(), serviceAddress); private String httpServiceAddress;
}
} public void start() throws Exception {
} // start server
}); if (isHttp) {
server.setStopedCallback(new BaseCallback() { // serviceRegistry stoped httpServiceAddress = IpUtil.getIpPort(this.ip,this.serverPort);
@Override }
public void run() { serviceAddress = IpUtil.getIpPort(this.ip, port);
// stop registry
if (serviceRegistry != null) { server = netType.serverClass.newInstance();
if (serviceData.size() > 0) { server.setStartedCallback(new BaseCallback() { // serviceRegistry started
serviceRegistry.remove(serviceData.keySet(), serviceAddress); @Override
} public void run() throws Exception {
serviceRegistry.stop(); // start registry
serviceRegistry = null; if (serviceRegistryClass != null) {
} serviceRegistry = serviceRegistryClass.newInstance();
} serviceRegistry.start(serviceRegistryParam);
}); if (serviceData.size() > 0) {
server.start(this);
} Map<String, String> keyServerAddress = new HashMap<>(16);
for (Map.Entry<String, Object> entry : serviceData.entrySet()) {
public void stop() throws Exception { //提供http请求的是服务的id,不包含.
// stop server if(entry.getKey().contains(".")){
server.stop(); keyServerAddress.put(entry.getKey(), serviceAddress);
} }else {
keyServerAddress.put(entry.getKey(),httpServiceAddress);
}
// ---------------------- server invoke ---------------------- }
serviceRegistry.registry(keyServerAddress);
/** }
* init local rpc service map }
*/ }
private Map<String, Object> serviceData = new HashMap<String, Object>(); });
public Map<String, Object> getServiceData() { server.setStopedCallback(new BaseCallback() { // serviceRegistry stoped
return serviceData; @Override
} public void run() {
// stop registry
/** if (serviceRegistry != null) {
* make service key if (serviceData.size() > 0) {
* serviceRegistry.remove(serviceData.keySet(), serviceAddress);
* @param iface }
* @param version serviceRegistry.stop();
* @return serviceRegistry = null;
*/ }
public static String makeServiceKey(String iface, String version){ }
String serviceKey = iface; });
if (version!=null && version.trim().length()>0) { server.start(this);
serviceKey += "#".concat(version); }
}
return serviceKey; public void stop() throws Exception {
} // stop server
server.stop();
/** }
* add service
*
* @param iface // ---------------------- server invoke ----------------------
* @param version
* @param serviceBean /**
*/ * init local rpc service map
public void addService(String iface, String version, Object serviceBean){ */
String serviceKey = makeServiceKey(iface, version); private Map<String, Object> serviceData = new HashMap<>();
serviceData.put(serviceKey, serviceBean);
public Map<String, Object> getServiceData() {
logger.info(">>>>>>>>>>> myth-rpc, provider factory add service success. serviceKey = {}, serviceBean = {}", serviceKey, serviceBean.getClass()); return serviceData;
} }
/** /**
* invoke service * make service key
* *
* @param rpcRequest * @param iface
* @return * @param version
*/ * @return
public RpcResponse invokeService(RpcRequest rpcRequest) { */
public static String makeServiceKey(String iface, String version) {
// make response String serviceKey = iface;
RpcResponse rpcResponse = new RpcResponse(); if (version != null && version.trim().length() > 0) {
rpcResponse.setRequestId(rpcRequest.getRequestId()); serviceKey += "#".concat(version);
}
// match service bean return serviceKey;
String serviceKey = makeServiceKey(rpcRequest.getClassName(), rpcRequest.getVersion()); }
Object serviceBean = serviceData.get(serviceKey);
/**
// valid * add service
if (serviceBean == null) { *
rpcResponse.setErrorMsg("The serviceKey["+ serviceKey +"] not found."); * @param iface
return rpcResponse; * @param version
} * @param serviceBean
*/
if (System.currentTimeMillis() - rpcRequest.getCreateMillisTime() > 3*60*1000) { public void addService(String iface, String version, Object serviceBean) {
rpcResponse.setErrorMsg("The timestamp difference between admin and executor exceeds the limit."); String serviceKey = makeServiceKey(iface, version);
return rpcResponse; serviceData.put(serviceKey, serviceBean);
}
if (accessToken!=null && accessToken.trim().length()>0 && !accessToken.trim().equals(rpcRequest.getAccessToken())) { logger.info(">>>>>>>>>>> myth-rpc, provider factory add service success. serviceKey = {}, serviceBean = {}", serviceKey, serviceBean.getClass());
rpcResponse.setErrorMsg("The access token[" + rpcRequest.getAccessToken() + "] is wrong."); }
return rpcResponse;
} /**
* invoke service
try { *
// invoke * @param rpcRequest
Class<?> serviceClass = serviceBean.getClass(); * @return
String methodName = rpcRequest.getMethodName(); */
Class<?>[] parameterTypes = rpcRequest.getParameterTypes(); public RpcResponse invokeService(RpcRequest rpcRequest) {
Object[] parameters = rpcRequest.getParameters();
// make response
RpcResponse rpcResponse = new RpcResponse();
rpcResponse.setRequestId(rpcRequest.getRequestId());
// match service bean
String serviceKey = makeServiceKey(rpcRequest.getClassName(), rpcRequest.getVersion());
Object serviceBean = serviceData.get(serviceKey);
// valid
if (serviceBean == null) {
rpcResponse.setErrorMsg("The serviceKey[" + serviceKey + "] not found.");
return rpcResponse;
}
if (System.currentTimeMillis() - rpcRequest.getCreateMillisTime() > 3 * 60 * 1000) {
rpcResponse.setErrorMsg("The timestamp difference between admin and executor exceeds the limit.");
return rpcResponse;
}
if (accessToken != null && accessToken.trim().length() > 0 && !accessToken.trim().equals(rpcRequest.getAccessToken())) {
rpcResponse.setErrorMsg("The access token[" + rpcRequest.getAccessToken() + "] is wrong.");
return rpcResponse;
}
try {
// invoke
Class<?> serviceClass = serviceBean.getClass();
String methodName = rpcRequest.getMethodName();
Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
Object[] parameters = rpcRequest.getParameters();
Method method = serviceClass.getMethod(methodName, parameterTypes); Method method = serviceClass.getMethod(methodName, parameterTypes);
method.setAccessible(true); method.setAccessible(true);
Object result = method.invoke(serviceBean, parameters); Object result = method.invoke(serviceBean, parameters);
/*FastClass serviceFastClass = FastClass.create(serviceClass);
FastMethod serviceFastMethod = serviceFastClass.getMethod(methodName, parameterTypes);
Object result = serviceFastMethod.invoke(serviceBean, parameters);*/
rpcResponse.setResult(result); rpcResponse.setResult(result);
} catch (Throwable t) { } catch (Throwable t) {
// catch error // catch error
logger.error("myth-rpc provider invokeService error.", t); logger.error("myth-rpc provider invokeService error.", t);
rpcResponse.setErrorMsg(ThrowableUtil.toString(t)); rpcResponse.setErrorMsg(ThrowableUtil.toString(t));
} }
return rpcResponse; return rpcResponse;
} }
} }
...@@ -11,9 +11,14 @@ import java.lang.annotation.*; ...@@ -11,9 +11,14 @@ import java.lang.annotation.*;
@Inherited @Inherited
public @interface RpcService { public @interface RpcService {
String version() default "";
/** /**
* @return * 提供http服务
* 向注册中心注册 服务的id 同一个业务中必须唯一
* 端口号从配置文件中获取springboot的端口号
*/ */
String version() default ""; boolean http_type() default false;
} }
...@@ -9,6 +9,7 @@ import com.byit.rpc.util.RpcException; ...@@ -9,6 +9,7 @@ import com.byit.rpc.util.RpcException;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
...@@ -16,9 +17,8 @@ import java.util.Map; ...@@ -16,9 +17,8 @@ import java.util.Map;
/** /**
* myth-rpc provider (for spring) * myth-rpc provider (for spring)
*
*/ */
public class RpcSpringProviderFactory extends RpcProviderFactory implements ApplicationContextAware, InitializingBean,DisposableBean { public class RpcSpringProviderFactory extends RpcProviderFactory implements ApplicationContextAware, InitializingBean, DisposableBean {
// ---------------------- config ---------------------- // ---------------------- config ----------------------
...@@ -28,13 +28,22 @@ public class RpcSpringProviderFactory extends RpcProviderFactory implements Appl ...@@ -28,13 +28,22 @@ public class RpcSpringProviderFactory extends RpcProviderFactory implements Appl
private int corePoolSize; private int corePoolSize;
private int maxPoolSize; private int maxPoolSize;
private String ip; // for registry private String ip; // for registry
private int port; // default port private int port; // default port
private String accessToken; private String accessToken;
private Class<? extends ServiceRegistry> serviceRegistryClass; // class.forname private Class<? extends ServiceRegistry> serviceRegistryClass; // class.forname
private Map<String, String> serviceRegistryParam; private Map<String, String> serviceRegistryParam;
@Value("${server.port}")
private int serverPort;
@Value("${spring.application.name}")
private String serverName;
/**
* 该服务是否提供http服务
*/
private Boolean isHttp = false;
// set // set
public void setNetType(String netType) { public void setNetType(String netType) {
...@@ -85,15 +94,16 @@ public class RpcSpringProviderFactory extends RpcProviderFactory implements Appl ...@@ -85,15 +94,16 @@ public class RpcSpringProviderFactory extends RpcProviderFactory implements Appl
// util // util
private void prepareConfig(){ private void prepareConfig() {
// prepare config // prepare config
NetEnum netTypeEnum = NetEnum.autoMatch(netType, null); NetEnum netTypeEnum = NetEnum.autoMatch(netType, null);
Serializer.SerializeEnum serializeEnum = Serializer.SerializeEnum.match(serialize, null); Serializer.SerializeEnum serializeEnum = Serializer.SerializeEnum.match(serialize, null);
Serializer serializer = serializeEnum!=null?serializeEnum.getSerializer():null; Serializer serializer = serializeEnum != null ? serializeEnum.getSerializer() : null;
// init config // init config
super.initConfig(netTypeEnum, serializer, corePoolSize, maxPoolSize, ip, port, accessToken, serviceRegistryClass, serviceRegistryParam); super.initConfig(netTypeEnum, serializer, corePoolSize, maxPoolSize, ip, port, isHttp, serverPort, serverName
, accessToken, serviceRegistryClass, serviceRegistryParam);
} }
...@@ -103,24 +113,28 @@ public class RpcSpringProviderFactory extends RpcProviderFactory implements Appl ...@@ -103,24 +113,28 @@ public class RpcSpringProviderFactory extends RpcProviderFactory implements Appl
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(RpcService.class); Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(RpcService.class);
if (serviceBeanMap!=null && serviceBeanMap.size()>0) { if (serviceBeanMap != null && serviceBeanMap.size() > 0) {
for (Object serviceBean : serviceBeanMap.values()) { for (Object serviceBean : serviceBeanMap.values()) {
// valid // valid
if (serviceBean.getClass().getInterfaces().length ==0) { if (serviceBean.getClass().getInterfaces().length == 0) {
throw new RpcException("myth-rpc, service(RpcService) must inherit interface."); throw new RpcException("myth-rpc, service(RpcService) must inherit interface.");
} }
// add service // add service
RpcService xxlRpcService = serviceBean.getClass().getAnnotation(RpcService.class); RpcService rpcService = serviceBean.getClass().getAnnotation(RpcService.class);
String iface = serviceBean.getClass().getInterfaces()[0].getName(); String iface = serviceBean.getClass().getInterfaces()[0].getName();
String version = xxlRpcService.version(); String version = rpcService.version();
//如果提供的是htp服务
if (rpcService.http_type()) {
this.isHttp = true;
super.addService(serverName, version, serviceBean);
} else {
super.addService(iface, version, serviceBean);
}
super.addService(iface, version, serviceBean);
} }
} }
// TODO,addServices by api + prop
} }
@Override @Override
......
# myth-rpc
myth-rpc.remoting.port=9998
myth-rpc.registry.address=http://localhost:8080/myth-register
myth-rpc.registry.env=liyuan
myth-rpc.registry.biz=byit-myth-job
logging.config=classpath:logback.xml
\ No newline at end of file
# myth-rpc
myth-rpc.remoting.port=9998
myth-rpc.registry.address=http://localhost:8080/myth-register
myth-rpc.registry.env=pre
myth-rpc.registry.biz=byit-myth-job
logging.config=classpath:logback.xml
\ No newline at end of file
# myth-rpc
myth-rpc.remoting.port=9998
myth-rpc.registry.address=http://localhost:8080/myth-register
myth-rpc.registry.env=test
myth-rpc.registry.biz=byit-myth-job
logging.config=classpath:logback.xml
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment