提交 e2e26dbe 编写于 作者: S shuang.kou

[v3.0]use @Slf4j of lombok and optimize some code

上级 b3edce5b
/.idea/
/target/
/rpc-framework-simple/target/
/rpc-framework-common/target/
/hello-service-api/target/
......
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
"http://checkstyle.sourceforge.net/dtds/configuration_1_3.dtd">
<module name="NewlineAtEndOfFile">
<property name="lineSeparator" value="lf"/>
</module>
<!--
<module name="RegexpSingleline">
<!-- Checks that FIXME is not used in comments. TODO is preferred.
-->
<property name="format" value="((//.*)|(\*.*))FIXME"/>
<property name="message"
value='TODO is preferred to FIXME. e.g. "TODO(johndoe): Refactor when v2 is released."'/>
</module>
Checkstyle configuration that checks the sun coding conventions from:
<module name="RegexpSingleline">
<!-- Checks that TODOs are named. (Actually, just that they are followed
by an open paren.)
-->
<property name="format" value="((//.*)|(\*.*))TODO[^(]"/>
<property name="message"
value='All TODOs should be named. e.g. "TODO(johndoe): Refactor when v2 is released."'/>
</module>
- the Java Language Specification at
http://java.sun.com/docs/books/jls/second_edition/html/index.html
<module name="TreeWalker">
<module name="LineLength">
<!-- Checks if a line is too long. -->
<property name="max" value="150" default="100"/>
<property name="severity" value="error"/>
</module>
<module name="RedundantImport">
<!-- Checks for redundant import statements. -->
<property name="severity" value="error"/>
</module>
<!-- Item 38 - Adhere to generally accepted naming conventions -->
<module name="PackageName">
<!-- Validates identifiers for package names against the
supplied expression. -->
<!-- Here the default checkstyle rule restricts package name parts to
seven characters, this is not in line with common practice at Google.
-->
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]{1,})*$"/>
<property name="severity" value="warning"/>
</module>
- the Sun Code Conventions at http://java.sun.com/docs/codeconv/
<module name="TypeNameCheck">
<!-- Validates static, final fields against the
expression "^[A-Z][a-zA-Z0-9]*$". -->
<metadata name="altname" value="TypeName"/>
<property name="severity" value="warning"/>
</module>
- the Javadoc guidelines at
http://java.sun.com/j2se/javadoc/writingdoccomments/index.html
<module name="ConstantNameCheck">
<!-- Validates non-private, static, final fields against the supplied
public/package final fields "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$". -->
<metadata name="altname" value="ConstantName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="false"/>
<property name="format" value="^([A-Z][A-Z0-9]*(_[A-Z0-9]+)*|FLAG_.*)$"/>
<message key="name.invalidPattern"
value="Variable ''{0}'' should be in ALL_CAPS (if it is a constant) or be private (otherwise)."/>
<property name="severity" value="warning"/>
</module>
- the JDK Api documentation http://java.sun.com/j2se/docs/api/index.html
<module name="StaticVariableNameCheck">
<!-- Validates static, non-final fields against the supplied
expression "^[a-z][a-zA-Z0-9]*_?$". -->
<metadata name="altname" value="StaticVariableName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="true"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*_?$"/>
<property name="severity" value="warning"/>
</module>
- some best practices
<module name="MemberNameCheck">
<!-- Validates non-static members against the supplied expression. -->
<metadata name="altname" value="MemberName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="true"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
<property name="severity" value="warning"/>
</module>
Checkstyle is very configurable. Be sure to read the documentation at
http://checkstyle.sf.net (or in your downloaded distribution).
<module name="MethodNameCheck">
<!-- Validates identifiers for method names. -->
<metadata name="altname" value="MethodName"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*(_[a-zA-Z0-9]+)*$"/>
<property name="severity" value="warning"/>
</module>
Most Checks are configurable, be sure to consult the documentation.
<module name="ParameterName">
<!-- Validates identifiers for method parameters against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
To completely disable a check, just comment it out or delete it from the file.
<module name="LocalFinalVariableName">
<!-- Validates identifiers for local final variables against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
Finally, it is worth reading the documentation.
<module name="LocalVariableName">
<!-- Validates identifiers for local variables against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<!--
-->
LENGTH and CODING CHECKS
-->
<module name="LeftCurly">
<!-- Checks for placement of the left curly brace ('{'). -->
<property name="severity" value="warning"/>
</module>
<module name="RightCurly">
<property name="option" value="same"/>
<property name="severity" value="warning"/>
</module>
<module name="Checker">
<!--
If you set the basedir property below, then all reported file
names will be relative to the specified directory. See
http://checkstyle.sourceforge.net/5.x/config.html#Checker
<!-- Checks for braces around if and else blocks -->
<module name="NeedBraces">
<property name="severity" value="warning"/>
<property name="tokens" value="LITERAL_IF, LITERAL_ELSE, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO"/>
</module>
<property name="basedir" value="${basedir}"/>
-->
<module name="UpperEll">
<!-- Checks that long constants are defined with an upper ell.-->
<property name="severity" value="error"/>
</module>
<property name="fileExtensions" value="java, properties, xml"/>
<module name="FallThrough">
<!-- Warn about falling through to the next case statement. Similar to
javac -Xlint:fallthrough, but the check is suppressed if a single-line comment
on the last non-blank line preceding the fallen-into case contains 'fall through' (or
some other variants which we don't publicized to promote consistency).
-->
<property name="reliefPattern"
value="fall through|Fall through|fallthru|Fallthru|falls through|Falls through|fallthrough|Fallthrough|No break|NO break|no break|continue on"/>
<property name="severity" value="error"/>
</module>
<!-- Checks that a resource-info.java file exists for each resource. -->
<!-- See http://checkstyle.sf.net/config_javadoc.html#JavadocPackage -->
<!--<module name="JavadocPackage"/>-->
<!-- Checks whether files end with a new line. -->
<!-- See http://checkstyle.sf.net/config_misc.html#NewlineAtEndOfFile -->
<!--
<!-- Checks that property files contain the same keys. -->
<!-- See http://checkstyle.sf.net/config_misc.html#Translation -->
<module name="NewlineAtEndOfFile">
<property name="severity" value="ignore"/>
</module>
<module name="Translation"/>
MODIFIERS CHECKS
<!-- Checks for Size Violations. -->
<!-- See http://checkstyle.sf.net/config_sizes.html -->
<module name="LineLength">
<property name="max" value="240"/>
</module>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
<module name="FileTabCharacter"/>
-->
<!-- Miscellaneous other checks. -->
<!-- See http://checkstyle.sf.net/config_misc.html -->
<module name="RegexpSingleline">
<property name="format" value="\s+$"/>
<property name="minimum" value="0"/>
<property name="maximum" value="0"/>
<property name="message" value="Line has trailing spaces."/>
</module>
<!-- <module name="ModifierOrder">-->
<!-- &lt;!&ndash; Warn if modifier order is inconsistent with JLS3 8.1.1, 8.3.1, and-->
<!-- 8.4.3. The prescribed order is:-->
<!-- public, protected, private, abstract, static, final, transient, volatile,-->
<!-- synchronized, native, strictfp-->
<!-- &ndash;&gt;-->
<!-- </module>-->
<!-- Checks for Headers -->
<!-- See http://checkstyle.sf.net/config_header.html -->
<!-- <module name="Header"> -->
<!-- <property name="headerFile" value="${checkstyle.header.file}"/> -->
<!-- <property name="fileExtensions" value="java"/> -->
<!-- </module> -->
<module name="SuppressWarningsFilter"/>
<module name="TreeWalker">
<module name="SuppressWarningsHolder"/>
<!-- Checks for Javadoc comments. -->
<!-- See http://checkstyle.sf.net/config_javadoc.html -->
<!--
WHITESPACE CHECKS
<module name="JavadocMethod"/>
<module name="JavadocType"/>
<module name="JavadocVariable"/>
<module name="JavadocStyle"/>
-->
<module name="WhitespaceAround">
<!-- Checks that various tokens are surrounded by whitespace.
This includes most binary operators and keywords followed
by regular or curly braces.
-->
<property name="tokens" value="ASSIGN, BAND, BAND_ASSIGN, BOR,
BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN,
EQUAL, GE, GT, LAND, LE, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE,
LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, LITERAL_RETURN,
LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS,
MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION,
SL, SL_ASSIGN, SR_ASSIGN, STAR, STAR_ASSIGN"/>
<property name="severity" value="error"/>
</module>
<module name="WhitespaceAfter">
<!-- Checks that commas, semicolons and typecasts are followed by
whitespace.
-->
<property name="tokens" value="COMMA, SEMI, TYPECAST"/>
</module>
<module name="NoWhitespaceAfter">
<!-- Checks that there is no whitespace after various unary operators.
Linebreaks are allowed.
-->
<property name="tokens" value="BNOT, DEC, DOT, INC, LNOT, UNARY_MINUS,
UNARY_PLUS"/>
<property name="allowLineBreaks" value="true"/>
<property name="severity" value="error"/>
</module>
<module name="NoWhitespaceBefore">
<!-- Checks that there is no whitespace before various unary operators.
Linebreaks are allowed.
-->
<property name="tokens" value="SEMI, DOT, POST_DEC, POST_INC"/>
<property name="allowLineBreaks" value="true"/>
<!-- Checks for Naming Conventions. -->
<!-- See http://checkstyle.sf.net/config_naming.html -->
<module name="ConstantName"/>
<module name="LocalFinalVariableName"/>
<module name="LocalVariableName"/>
<module name="MemberName"/>
<module name="MethodName"/>
<module name="PackageName"/>
<module name="ParameterName"/>
<module name="StaticVariableName"/>
<module name="TypeName"/>
<!-- Checks for imports -->
<!-- See http://checkstyle.sf.net/config_import.html -->
<!--<module name="AvoidStarImport"/>-->
<module name="RedundantImport">
<!-- Checks for redundant import statements. -->
<property name="severity" value="error"/>
</module>
<module name="ParenPad">
<!-- Checks that there is no whitespace before close parens or after
open parens.
-->
<property name="severity" value="warning"/>
</module>
<!-- Checks for Size Violations. -->
<!-- See http://checkstyle.sf.net/config_sizes.html -->
<module name="MethodLength"/>
<module name="ParameterNumber">
<property name="max" value="16"/>
<property name="ignoreOverriddenMethods" value="true"/>
</module>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
<module name="EmptyForIteratorPad"/>
<module name="GenericWhitespace"/>
<module name="MethodParamPad"/>
<module name="NoWhitespaceAfter"/>
<module name="NoWhitespaceBefore"/>
<module name="OperatorWrap"/>
<module name="ParenPad"/>
<module name="TypecastParenPad"/>
<module name="WhitespaceAfter"/>
<module name="WhitespaceAround"/>
<!-- Modifier Checks -->
<!-- See http://checkstyle.sf.net/config_modifiers.html -->
<module name="ModifierOrder"/>
<module name="RedundantModifier"/>
<!-- Checks for blocks. You know, those {}'s -->
<!-- See http://checkstyle.sf.net/config_blocks.html -->
<module name="AvoidNestedBlocks"/>
<module name="EmptyBlock"/>
<module name="LeftCurly"/>
<module name="NeedBraces"/>
<module name="RightCurly"/>
<!-- Checks for common coding problems -->
<!-- See http://checkstyle.sf.net/config_coding.html -->
<!--<module name="AvoidInlineConditionals"/>-->
<module name="EmptyStatement"/>
<module name="EqualsHashCode"/>
<!--<module name="HiddenField"/>-->
<module name="IllegalInstantiation"/>
<module name="InnerAssignment"/>
<!--<module name="MagicNumber"/>-->
<module name="MissingSwitchDefault"/>
<module name="SimplifyBooleanExpression"/>
<module name="SimplifyBooleanReturn"/>
<!-- Checks for class design -->
<!-- See http://checkstyle.sf.net/config_design.html -->
<!--<module name="DesignForExtension"/>-->
<module name="FinalClass"/>
<module name="InterfaceIsType"/>
<module name="VisibilityModifier"/>
<!-- Miscellaneous other checks. -->
<!-- See http://checkstyle.sf.net/config_misc.html -->
<module name="ArrayTypeStyle"/>
<module name="TodoComment"/>
<module name="UpperEll"/>
</module>
</module>
package github.javaguide;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
/**
* @author shuang.kou
* @createTime 2020年05月10日 07:52:00
*/
@Slf4j
public class HelloServiceImpl implements HelloService {
private static final Logger logger = LoggerFactory.getLogger(HelloServiceImpl.class);
@Override
public String hello(Hello hello) {
logger.info("HelloServiceImpl收到: {}.", hello.getMessage());
log.info("HelloServiceImpl收到: {}.", hello.getMessage());
String result = "Hello description is " + hello.getDescription();
logger.info("HelloServiceImpl返回: {}.", result);
log.info("HelloServiceImpl返回: {}.", result);
return result;
}
}
......@@ -24,7 +24,7 @@
<junit.jupiter.version>5.5.2</junit.jupiter.version>
<junit.platform.version>1.5.2</junit.platform.version>
<!-- checkstyle -->
<checkstyle-maven-plugin.version>3.0.0</checkstyle-maven-plugin.version>
<checkstyle-maven-plugin.version>3.1.1</checkstyle-maven-plugin.version>
</properties>
<modules>
<module>rpc-framework-simple</module>
......@@ -127,6 +127,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
......
......@@ -5,15 +5,14 @@ import github.javaguide.dto.RpcResponse;
import github.javaguide.enumeration.RpcErrorMessageEnum;
import github.javaguide.enumeration.RpcResponseCode;
import github.javaguide.exception.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
/**
* @author shuang.kou
* @createTime 2020年05月26日 18:03:00
*/
public class RpcMessageChecker {
private static final Logger logger = LoggerFactory.getLogger(RpcMessageChecker.class);
@Slf4j
public final class RpcMessageChecker {
private static final String INTERFACE_NAME = "interfaceName";
private RpcMessageChecker() {
......@@ -21,17 +20,14 @@ public class RpcMessageChecker {
public static void check(RpcResponse rpcResponse, RpcRequest rpcRequest) {
if (rpcResponse == null) {
logger.error("调用服务失败,rpcResponse 为 null,serviceName:{}", rpcRequest.getInterfaceName());
throw new RpcException(RpcErrorMessageEnum.SERVICE_INVOCATION_FAILURE, INTERFACE_NAME + ":" + rpcRequest.getInterfaceName());
}
if (!rpcRequest.getRequestId().equals(rpcResponse.getRequestId())) {
logger.error("调用服务失败,rpcRequest 和 rpcResponse 对应不上,serviceName:{},RpcResponse:{}", rpcRequest.getInterfaceName(), rpcResponse);
throw new RpcException(RpcErrorMessageEnum.REQUEST_NOT_MATCH_RESPONSE, INTERFACE_NAME + ":" + rpcRequest.getInterfaceName());
}
if (rpcResponse.getCode() == null || !rpcResponse.getCode().equals(RpcResponseCode.SUCCESS.getCode())) {
logger.error("调用服务失败,serviceName:{},RpcResponse:{}", rpcRequest.getInterfaceName(), rpcResponse);
throw new RpcException(RpcErrorMessageEnum.SERVICE_INVOCATION_FAILURE, INTERFACE_NAME + ":" + rpcRequest.getInterfaceName());
}
}
......
......@@ -16,7 +16,7 @@ import java.util.concurrent.TimeUnit;
* @author shuang.kou
* @createTime 2020年05月26日 16:00:00
*/
public class ThreadPoolFactory {
public final class ThreadPoolFactory {
/**
* 线程池参数
*/
......
package github.javaguide.utils.factory;
import java.util.HashMap;
import java.util.Map;
/**
* 获取单例对象的工厂类
*
* @author shuang.kou
* @createTime 2020年06月03日 15:04:00
*/
public final class SingletonFactory {
private static Map<String, Object> objectMap = new HashMap<>();
private SingletonFactory() {
}
public static <T> T getInstance(Class<T> c) {
String key = c.toString();
Object instance = objectMap.get(key);
synchronized (c) {
if (instance == null) {
try {
instance = c.newInstance();
objectMap.put(key, instance);
} catch (IllegalAccessException | InstantiationException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
return c.cast(instance);
}
}
package github.javaguide.utils.zk;
import github.javaguide.exception.RpcException;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
......@@ -19,61 +18,62 @@ import java.util.concurrent.ConcurrentHashMap;
* @author shuang.kou
* @createTime 2020年05月31日 11:38:00
*/
public class CuratorHelper {
private static final Logger logger = LoggerFactory.getLogger(CuratorHelper.class);
private static final int SLEEP_MS_BETWEEN_RETRIES = 100;
private static final int MAX_RETRIES = 3;
@Slf4j
public final class CuratorHelper {
private static final int BASE_SLEEP_TIME = 1000;
private static final int MAX_RETRIES = 5;
private static final String CONNECT_STRING = "127.0.0.1:2181";
private static final int CONNECTION_TIMEOUT_MS = 10 * 1000;
private static final int SESSION_TIMEOUT_MS = 60 * 1000;
public static final String ZK_REGISTER_ROOT_PATH = "/my-rpc";
private static Map<String, List<String>> serviceAddressMap = new ConcurrentHashMap<>();
private static CuratorFramework zkClient = getZkClient();
private CuratorHelper() {
}
public static CuratorFramework getZkClient() {
// 重试策略,重试3次,并在两次重试之间等待100毫秒,以防出现连接问题。
RetryPolicy retryPolicy = new RetryNTimes(
MAX_RETRIES, SLEEP_MS_BETWEEN_RETRIES);
return CuratorFrameworkFactory.builder()
// 重试策略。重试3次,并且会增加重试之间的睡眠时间。
RetryPolicy retryPolicy = new ExponentialBackoffRetry(BASE_SLEEP_TIME, MAX_RETRIES);
CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
//要连接的服务器(可以是服务器列表)
.connectString(CONNECT_STRING)
.retryPolicy(retryPolicy)
//连接超时时间,10秒
.connectionTimeoutMs(CONNECTION_TIMEOUT_MS)
//会话超时时间,60秒
.sessionTimeoutMs(SESSION_TIMEOUT_MS)
.build();
curatorFramework.start();
return curatorFramework;
}
/**
* 创建临时节点
* 临时节点驻存在ZooKeeper中,当连接和session断掉时被删除。
*/
public static void createEphemeralNode(final CuratorFramework zkClient, final String path) {
public static void createEphemeralNode(String path) {
try {
zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path);
if (zkClient.checkExists().forPath(path) == null) {
zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path);
log.info("节点创建成功,节点为:[{}]", path);
} else {
log.info("节点已经存在,节点为:[{}]", path);
}
} catch (Exception e) {
logger.error("occur exception:", e);
throw new RpcException(e.getMessage(), e.getCause());
}
}
/**
* 获取某个字节下的子节点,也就是获取所有提供服务的生产者的地址
*/
public static List<String> getChildrenNodes(final CuratorFramework zkClient, final String serviceName) {
public static List<String> getChildrenNodes(String serviceName) {
if (serviceAddressMap.containsKey(serviceName)) {
return serviceAddressMap.get(serviceName);
}
List<String> result = Collections.emptyList();
List<String> result;
String servicePath = CuratorHelper.ZK_REGISTER_ROOT_PATH + "/" + serviceName;
try {
result = zkClient.getChildren().forPath(servicePath);
serviceAddressMap.put(serviceName, result);
registerWatcher(zkClient, serviceName);
} catch (Exception e) {
logger.error("occur exception:", e);
throw new RpcException(e.getMessage(), e.getCause());
}
return result;
}
......@@ -94,7 +94,7 @@ public class CuratorHelper {
try {
pathChildrenCache.start();
} catch (Exception e) {
logger.error("occur exception:", e);
log.error("occur exception:", e);
}
}
}
......@@ -6,8 +6,7 @@ import github.javaguide.enumeration.RpcResponseCode;
import github.javaguide.exception.RpcException;
import github.javaguide.provider.ServiceProvider;
import github.javaguide.provider.ServiceProviderImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
......@@ -18,13 +17,9 @@ import java.lang.reflect.Method;
* @author shuang.kou
* @createTime 2020年05月13日 09:05:00
*/
@Slf4j
public class RpcRequestHandler {
private static final Logger logger = LoggerFactory.getLogger(RpcRequestHandler.class);
private static final ServiceProvider SERVICE_PROVIDER;
static {
SERVICE_PROVIDER = new ServiceProviderImpl();
}
private static ServiceProvider serviceProvider = new ServiceProviderImpl();
/**
* 处理 rpcRequest :调用对应的方法,然后返回方法执行结果
......@@ -32,9 +27,9 @@ public class RpcRequestHandler {
public Object handle(RpcRequest rpcRequest) {
Object result;
//通过注册中心获取到目标类(客户端需要调用类)
Object service = SERVICE_PROVIDER.getServiceProvider(rpcRequest.getInterfaceName());
Object service = serviceProvider.getServiceProvider(rpcRequest.getInterfaceName());
result = invokeTargetMethod(rpcRequest, service);
logger.info("service:{} successful invoke method:{}", rpcRequest.getInterfaceName(), rpcRequest.getMethodName());
log.info("service:{} successful invoke method:{}", rpcRequest.getInterfaceName(), rpcRequest.getMethodName());
return result;
}
......@@ -48,7 +43,7 @@ public class RpcRequestHandler {
private Object invokeTargetMethod(RpcRequest rpcRequest, Object service) {
Object result;
try {
Method method =service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
if (null == method) {
return RpcResponse.fail(RpcResponseCode.NOT_FOUND_METHOD);
}
......
......@@ -2,8 +2,7 @@ package github.javaguide.provider;
import github.javaguide.enumeration.RpcErrorMessageEnum;
import github.javaguide.exception.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
import java.util.Set;
......@@ -13,18 +12,17 @@ import java.util.concurrent.ConcurrentHashMap;
* @author shuang.kou
* @createTime 2020年05月13日 11:23:00
*/
@Slf4j
public class ServiceProviderImpl implements ServiceProvider {
private static final Logger logger = LoggerFactory.getLogger(ServiceProviderImpl.class);
/**
* 接口名和服务的对应关系
* note:处理一个接口被两个实现类实现的情况如何处理?
* note:处理一个接口被两个实现类实现的情况如何处理?(通过 group 分组)
* key:service/interface name
* value:service
*/
private static final Map<String, Object> serviceMap = new ConcurrentHashMap<>();
private static final Set<String> registeredService = ConcurrentHashMap.newKeySet();
private static Map<String, Object> serviceMap = new ConcurrentHashMap<>();
private static Set<String> registeredService = ConcurrentHashMap.newKeySet();
/**
* note:可以修改为扫描注解注册
......@@ -37,7 +35,7 @@ public class ServiceProviderImpl implements ServiceProvider {
}
registeredService.add(serviceName);
serviceMap.put(serviceName, service);
logger.info("Add service: {} and interfaces:{}", serviceName, service.getClass().getInterfaces());
log.info("Add service: {} and interfaces:{}", serviceName, service.getClass().getInterfaces());
}
@Override
......
......@@ -2,8 +2,7 @@ package github.javaguide.proxy;
import github.javaguide.dto.RpcRequest;
import github.javaguide.transport.ClientTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
......@@ -16,8 +15,8 @@ import java.util.UUID;
* @author shuang.kou
* @createTime 2020年05月10日 19:01:00
*/
@Slf4j
public class RpcClientProxy implements InvocationHandler {
private static final Logger logger = LoggerFactory.getLogger(RpcClientProxy.class);
/**
* 用于发送请求给服务端,对应socket和netty两种实现方式
*/
......@@ -40,7 +39,7 @@ public class RpcClientProxy implements InvocationHandler {
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
logger.info("Call invoke method and invoked method: {}", method.getName());
log.info("Call invoke method and invoked method: {}", method.getName());
RpcRequest rpcRequest = RpcRequest.builder().methodName(method.getName())
.parameters(args)
.interfaceName(method.getDeclaringClass().getName())
......
package github.javaguide.registry;
import github.javaguide.utils.zk.CuratorHelper;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
......@@ -13,21 +11,15 @@ import java.net.InetSocketAddress;
* @author shuang.kou
* @createTime 2020年06月01日 15:16:00
*/
@Slf4j
public class ZkServiceDiscovery implements ServiceDiscovery {
private static final Logger logger = LoggerFactory.getLogger(ZkServiceDiscovery.class);
private final CuratorFramework zkClient;
public ZkServiceDiscovery() {
this.zkClient = CuratorHelper.getZkClient();
zkClient.start();
}
@Override
public InetSocketAddress lookupService(String serviceName) {
// TODO(shuang.kou):feat: 负载均衡
// 这里直接去了第一个找到的服务地址
String serviceAddress = CuratorHelper.getChildrenNodes(zkClient, serviceName).get(0);
logger.info("成功找到服务地址:{}", serviceAddress);
String serviceAddress = CuratorHelper.getChildrenNodes(serviceName).get(0);
log.info("成功找到服务地址:{}", serviceAddress);
return new InetSocketAddress(serviceAddress.split(":")[0], Integer.parseInt(serviceAddress.split(":")[1]));
}
}
package github.javaguide.registry;
import github.javaguide.utils.zk.CuratorHelper;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
......@@ -13,14 +11,8 @@ import java.net.InetSocketAddress;
* @author shuang.kou
* @createTime 2020年05月31日 10:56:00
*/
@Slf4j
public class ZkServiceRegistry implements ServiceRegistry {
private static final Logger logger = LoggerFactory.getLogger(ZkServiceRegistry.class);
private final CuratorFramework zkClient;
public ZkServiceRegistry() {
zkClient = CuratorHelper.getZkClient();
zkClient.start();
}
@Override
public void registerService(String serviceName, InetSocketAddress inetSocketAddress) {
......@@ -28,7 +20,6 @@ public class ZkServiceRegistry implements ServiceRegistry {
StringBuilder servicePath = new StringBuilder(CuratorHelper.ZK_REGISTER_ROOT_PATH).append("/").append(serviceName);
//服务子节点下注册子节点:服务地址
servicePath.append(inetSocketAddress.toString());
CuratorHelper.createEphemeralNode(zkClient, servicePath.toString());
logger.info("节点创建成功,节点为:{}", servicePath);
CuratorHelper.createEphemeralNode(servicePath.toString());
}
}
......@@ -7,8 +7,7 @@ import github.javaguide.dto.RpcRequest;
import github.javaguide.dto.RpcResponse;
import github.javaguide.exception.SerializeException;
import github.javaguide.serialize.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
......@@ -19,8 +18,8 @@ import java.io.ByteArrayOutputStream;
* @author shuang.kou
* @createTime 2020年05月13日 19:29:00
*/
@Slf4j
public class KryoSerializer implements Serializer {
private static final Logger logger = LoggerFactory.getLogger(KryoSerializer.class);
/**
* 由于 Kryo 不是线程安全的。每个线程都应该有自己的 Kryo,Input 和 Output 实例。
......@@ -45,7 +44,6 @@ public class KryoSerializer implements Serializer {
kryoThreadLocal.remove();
return output.toBytes();
} catch (Exception e) {
logger.error("occur exception when serialize:", e);
throw new SerializeException("序列化失败");
}
}
......@@ -60,7 +58,6 @@ public class KryoSerializer implements Serializer {
kryoThreadLocal.remove();
return clazz.cast(o);
} catch (Exception e) {
logger.error("occur exception when deserialize:", e);
throw new SerializeException("反序列化失败");
}
}
......
......@@ -5,8 +5,7 @@ import github.javaguide.exception.RpcException;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
import java.util.Date;
......@@ -19,8 +18,8 @@ import java.util.concurrent.TimeUnit;
* @author shuang.kou
* @createTime 2020年05月29日 16:36:00
*/
@Slf4j
public class ChannelProvider {
private static final Logger logger = LoggerFactory.getLogger(ChannelProvider.class);
private static Bootstrap bootstrap = NettyClient.initializeBootstrap();
private static Channel channel = null;
......@@ -28,14 +27,14 @@ public class ChannelProvider {
* 最多重试次数
*/
private static final int MAX_RETRY_COUNT = 5;
public static Channel get(InetSocketAddress inetSocketAddress) {
CountDownLatch countDownLatch = new CountDownLatch(1);
try {
connect(bootstrap, inetSocketAddress, countDownLatch);
countDownLatch.await();
} catch (InterruptedException e) {
logger.error("occur exception when get channel:", e);
log.error("occur exception when get channel:", e);
}
return channel;
}
......@@ -51,13 +50,13 @@ public class ChannelProvider {
private static void connect(Bootstrap bootstrap, InetSocketAddress inetSocketAddress, int retry, CountDownLatch countDownLatch) {
bootstrap.connect(inetSocketAddress).addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
logger.info("客户端连接成功!");
log.info("客户端连接成功!");
channel = future.channel();
countDownLatch.countDown();
return;
}
if (retry == 0) {
logger.error("客户端连接失败:重试次数已用完,放弃连接!");
log.error("客户端连接失败:重试次数已用完,放弃连接!");
countDownLatch.countDown();
throw new RpcException(RpcErrorMessageEnum.CLIENT_CONNECT_SERVER_FAILURE);
}
......@@ -65,7 +64,7 @@ public class ChannelProvider {
int order = (MAX_RETRY_COUNT - retry) + 1;
// 本次重连的间隔
int delay = 1 << order;
logger.error("{}: 连接失败,第 {} 次重连……", new Date(), order);
log.error("{}: 连接失败,第 {} 次重连……", new Date(), order);
bootstrap.config().group().schedule(() -> connect(bootstrap, inetSocketAddress, retry - 1, countDownLatch), delay, TimeUnit
.SECONDS);
});
......
......@@ -12,8 +12,7 @@ import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
/**
* 用于初始化 和 关闭 Bootstrap 对象
......@@ -21,13 +20,10 @@ import org.slf4j.LoggerFactory;
* @author shuang.kou
* @createTime 2020年05月29日 17:51:00
*/
public class NettyClient {
private static final Logger logger = LoggerFactory.getLogger(NettyClient.class);
private static final Bootstrap b;
private static final EventLoopGroup eventLoopGroup;
@Slf4j
public final class NettyClient {
private static Bootstrap b;
private static EventLoopGroup eventLoopGroup;
private NettyClient() {
}
......@@ -59,7 +55,7 @@ public class NettyClient {
}
public static void close() {
logger.info("call close method");
log.info("call close method");
eventLoopGroup.shutdownGracefully();
}
......
......@@ -9,8 +9,7 @@ import github.javaguide.utils.checker.RpcMessageChecker;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicReference;
......@@ -21,8 +20,8 @@ import java.util.concurrent.atomic.AtomicReference;
* @author shuang.kou
* @createTime 2020年05月29日 11:34:00
*/
@Slf4j
public class NettyClientClientTransport implements ClientTransport {
private static final Logger logger = LoggerFactory.getLogger(NettyClientClientTransport.class);
private final ServiceDiscovery serviceDiscovery;
public NettyClientClientTransport() {
......@@ -38,16 +37,16 @@ public class NettyClientClientTransport implements ClientTransport {
if (channel.isActive()) {
channel.writeAndFlush(rpcRequest).addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
logger.info("client send message: {}", rpcRequest);
log.info("client send message: {}", rpcRequest);
} else {
future.channel().close();
logger.error("Send failed:", future.cause());
log.error("Send failed:", future.cause());
}
});
channel.closeFuture().sync();
AttributeKey<RpcResponse> key = AttributeKey.valueOf("rpcResponse" + rpcRequest.getRequestId());
RpcResponse rpcResponse = channel.attr(key).get();
logger.info("client get rpcResponse from channel:{}", rpcResponse);
log.info("client get rpcResponse from channel:{}", rpcResponse);
//校验 RpcResponse 和 RpcRequest
RpcMessageChecker.check(rpcResponse, rpcRequest);
result.set(rpcResponse.getData());
......@@ -57,7 +56,7 @@ public class NettyClientClientTransport implements ClientTransport {
}
} catch (InterruptedException e) {
logger.error("occur exception when send rpc message from client:", e);
log.error("occur exception when send rpc message from client:", e);
}
return result.get();
......
......@@ -6,8 +6,7 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
/**
* 自定义客户端 ChannelHandler 来处理服务端发过来的数据
......@@ -19,8 +18,8 @@ import org.slf4j.LoggerFactory;
* @author shuang.kou
* @createTime 2020年05月25日 20:50:00
*/
@Slf4j
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);
/**
* 读取服务端传输的消息
......@@ -28,7 +27,7 @@ public class NettyClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
try {
logger.info(String.format("client receive msg: %s", msg));
log.info("client receive msg: [{}]", msg);
RpcResponse rpcResponse = (RpcResponse) msg;
// 声明一个 AttributeKey 对象,类似于 Map 中的 key
AttributeKey<RpcResponse> key = AttributeKey.valueOf("rpcResponse" + rpcResponse.getRequestId());
......@@ -49,7 +48,7 @@ public class NettyClientHandler extends ChannelInboundHandlerAdapter {
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.error("client catch exception:", cause);
log.error("client catch exception:", cause);
cause.printStackTrace();
ctx.close();
}
......
......@@ -5,8 +5,7 @@ import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
......@@ -17,8 +16,8 @@ import java.util.List;
* @createTime 2020年05月25日 19:42:00
*/
@AllArgsConstructor
@Slf4j
public class NettyKryoDecoder extends ByteToMessageDecoder {
private static final Logger logger = LoggerFactory.getLogger(NettyKryoDecoder.class);
private Serializer serializer;
private Class<?> genericClass;
......@@ -47,7 +46,7 @@ public class NettyKryoDecoder extends ByteToMessageDecoder {
int dataLength = in.readInt();
//4.遇到不合理的情况直接 return
if (dataLength < 0 || in.readableBytes() < 0) {
logger.error("data length or byteBuf readableBytes is not valid");
log.error("data length or byteBuf readableBytes is not valid");
return;
}
//5.如果可读字节数小于消息长度的话,说明是不完整的消息,重置readIndex
......@@ -61,7 +60,7 @@ public class NettyKryoDecoder extends ByteToMessageDecoder {
// 将bytes数组转换为我们需要的对象
Object obj = serializer.deserialize(body, genericClass);
out.add(obj);
logger.info("successful decode ByteBuf to Object");
log.info("successful decode ByteBuf to Object");
}
}
}
......@@ -19,8 +19,7 @@ import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
......@@ -30,8 +29,8 @@ import java.net.InetSocketAddress;
* @author shuang.kou
* @createTime 2020年05月25日 16:42:00
*/
@Slf4j
public class NettyServer {
private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
private final String host;
private final int port;
private final KryoSerializer kryoSerializer;
......@@ -80,7 +79,7 @@ public class NettyServer {
// 等待服务端监听端口关闭
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
logger.error("occur exception when start server:", e);
log.error("occur exception when start server:", e);
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
......
......@@ -8,10 +8,9 @@ import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.concurrent.ExecutorService;
......@@ -24,28 +23,28 @@ import java.util.concurrent.ExecutorService;
* @author shuang.kou
* @createTime 2020年05月25日 20:44:00
*/
@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
private static final String THREAD_NAME_PREFIX = "netty-server-handler-rpc-pool";
private static final RpcRequestHandler rpcRequestHandler;
private static final ExecutorService threadPool;
private final RpcRequestHandler rpcRequestHandler;
private final ExecutorService threadPool;
static {
rpcRequestHandler = new RpcRequestHandler();
threadPool = ThreadPoolFactory.createDefaultThreadPool(THREAD_NAME_PREFIX);
public NettyServerHandler() {
this.rpcRequestHandler = new RpcRequestHandler();
this.threadPool = ThreadPoolFactory.createDefaultThreadPool(THREAD_NAME_PREFIX);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
threadPool.execute(() -> {
logger.info(String.format("server handle message from client by thread: %s", Thread.currentThread().getName()));
log.info(String.format("server handle message from client by thread: %s", Thread.currentThread().getName()));
try {
logger.info(String.format("server receive msg: %s", msg));
log.info(String.format("server receive msg: %s", msg));
RpcRequest rpcRequest = (RpcRequest) msg;
//执行目标方法(客户端需要执行的方法)并且返回方法结果
Object result = rpcRequestHandler.handle(rpcRequest);
logger.info(String.format("server get result: %s", result.toString()));
log.info(String.format("server get result: %s", result.toString()));
//返回方法执行结果给客户端
ChannelFuture f = ctx.writeAndFlush(RpcResponse.success(result, rpcRequest.getRequestId()));
f.addListener(ChannelFutureListener.CLOSE);
......@@ -59,7 +58,7 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.error("server catch exception");
log.error("server catch exception");
cause.printStackTrace();
ctx.close();
}
......
......@@ -8,8 +8,7 @@ import github.javaguide.registry.ZkServiceDiscovery;
import github.javaguide.transport.ClientTransport;
import github.javaguide.utils.checker.RpcMessageChecker;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.ObjectInputStream;
......@@ -24,8 +23,8 @@ import java.net.Socket;
* @createTime 2020年05月10日 18:40:00
*/
@AllArgsConstructor
@Slf4j
public class SocketRpcClient implements ClientTransport {
private static final Logger logger = LoggerFactory.getLogger(SocketRpcClient.class);
private final ServiceDiscovery serviceDiscovery;
public SocketRpcClient() {
......@@ -47,7 +46,7 @@ public class SocketRpcClient implements ClientTransport {
RpcMessageChecker.check(rpcResponse, rpcRequest);
return rpcResponse.getData();
} catch (IOException | ClassNotFoundException e) {
logger.error("occur exception when send sendRpcRequest");
log.error("occur exception when send sendRpcRequest");
throw new RpcException("调用服务失败:", e);
}
}
......
......@@ -3,8 +3,8 @@ package github.javaguide.transport.socket;
import github.javaguide.dto.RpcRequest;
import github.javaguide.dto.RpcResponse;
import github.javaguide.handler.RpcRequestHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import github.javaguide.utils.factory.SingletonFactory;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.ObjectInputStream;
......@@ -15,22 +15,20 @@ import java.net.Socket;
* @author shuang.kou
* @createTime 2020年05月10日 09:18:00
*/
@Slf4j
public class SocketRpcRequestHandlerRunnable implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(SocketRpcRequestHandlerRunnable.class);
private Socket socket;
private static final RpcRequestHandler rpcRequestHandler;
private RpcRequestHandler rpcRequestHandler;
static {
rpcRequestHandler = new RpcRequestHandler();
}
public SocketRpcRequestHandlerRunnable(Socket socket) {
this.socket = socket;
this.rpcRequestHandler = SingletonFactory.getInstance(RpcRequestHandler.class);
}
@Override
public void run() {
logger.info(String.format("server handle message from client by thread: %s", Thread.currentThread().getName()));
log.info("server handle message from client by thread: [{}]", Thread.currentThread().getName());
try (ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream())) {
RpcRequest rpcRequest = (RpcRequest) objectInputStream.readObject();
......@@ -38,7 +36,7 @@ public class SocketRpcRequestHandlerRunnable implements Runnable {
objectOutputStream.writeObject(RpcResponse.success(result, rpcRequest.getRequestId()));
objectOutputStream.flush();
} catch (IOException | ClassNotFoundException e) {
logger.error("occur exception:", e);
log.error("occur exception:", e);
}
}
......
......@@ -5,8 +5,7 @@ import github.javaguide.provider.ServiceProviderImpl;
import github.javaguide.registry.ServiceRegistry;
import github.javaguide.registry.ZkServiceRegistry;
import github.javaguide.utils.concurrent.ThreadPoolFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
......@@ -18,10 +17,10 @@ import java.util.concurrent.ExecutorService;
* @author shuang.kou
* @createTime 2020年05月10日 08:01:00
*/
@Slf4j
public class SocketRpcServer {
private final ExecutorService threadPool;
private static final Logger logger = LoggerFactory.getLogger(SocketRpcServer.class);
private final String host;
private final int port;
private final ServiceRegistry serviceRegistry;
......@@ -45,15 +44,15 @@ public class SocketRpcServer {
private void start() {
try (ServerSocket server = new ServerSocket()) {
server.bind(new InetSocketAddress(host, port));
logger.info("server starts...");
log.info("server starts...");
Socket socket;
while ((socket = server.accept()) != null) {
logger.info("client connected");
log.info("client connected");
threadPool.execute(new SocketRpcRequestHandlerRunnable(socket));
}
threadPool.shutdown();
} catch (IOException e) {
logger.error("occur IOException:", e);
log.error("occur IOException:", e);
}
}
......
#Wed Jun 03 12:17:39 CST 2020
configuration*?=3933E073ACC7FD802734C136E4E68225B8445E2F
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<module name="NewlineAtEndOfFile">
<property name="lineSeparator" value="lf"/>
</module>
<module name="RegexpSingleline">
<!-- Checks that FIXME is not used in comments. TODO is preferred.
-->
<property name="format" value="((//.*)|(\*.*))FIXME"/>
<property name="message"
value='TODO is preferred to FIXME. e.g. "TODO(johndoe): Refactor when v2 is released."'/>
</module>
<module name="RegexpSingleline">
<!-- Checks that TODOs are named. (Actually, just that they are followed
by an open paren.)
-->
<property name="format" value="((//.*)|(\*.*))TODO[^(]"/>
<property name="message"
value='All TODOs should be named. e.g. "TODO(johndoe): Refactor when v2 is released."'/>
</module>
<module name="TreeWalker">
<module name="LineLength">
<!-- Checks if a line is too long. -->
<property name="max" value="150" default="100"/>
<property name="severity" value="error"/>
</module>
<module name="RedundantImport">
<!-- Checks for redundant import statements. -->
<property name="severity" value="error"/>
</module>
<!-- Item 38 - Adhere to generally accepted naming conventions -->
<module name="PackageName">
<!-- Validates identifiers for package names against the
supplied expression. -->
<!-- Here the default checkstyle rule restricts package name parts to
seven characters, this is not in line with common practice at Google.
-->
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]{1,})*$"/>
<property name="severity" value="warning"/>
</module>
<module name="TypeNameCheck">
<!-- Validates static, final fields against the
expression "^[A-Z][a-zA-Z0-9]*$". -->
<metadata name="altname" value="TypeName"/>
<property name="severity" value="warning"/>
</module>
<module name="ConstantNameCheck">
<!-- Validates non-private, static, final fields against the supplied
public/package final fields "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$". -->
<metadata name="altname" value="ConstantName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="false"/>
<property name="format" value="^([A-Z][A-Z0-9]*(_[A-Z0-9]+)*|FLAG_.*)$"/>
<message key="name.invalidPattern"
value="Variable ''{0}'' should be in ALL_CAPS (if it is a constant) or be private (otherwise)."/>
<property name="severity" value="warning"/>
</module>
<module name="StaticVariableNameCheck">
<!-- Validates static, non-final fields against the supplied
expression "^[a-z][a-zA-Z0-9]*_?$". -->
<metadata name="altname" value="StaticVariableName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="true"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*_?$"/>
<property name="severity" value="warning"/>
</module>
<module name="MemberNameCheck">
<!-- Validates non-static members against the supplied expression. -->
<metadata name="altname" value="MemberName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="true"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
<property name="severity" value="warning"/>
</module>
<module name="MethodNameCheck">
<!-- Validates identifiers for method names. -->
<metadata name="altname" value="MethodName"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*(_[a-zA-Z0-9]+)*$"/>
<property name="severity" value="warning"/>
</module>
<module name="ParameterName">
<!-- Validates identifiers for method parameters against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<module name="LocalFinalVariableName">
<!-- Validates identifiers for local final variables against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<module name="LocalVariableName">
<!-- Validates identifiers for local variables against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<!--
LENGTH and CODING CHECKS
-->
<module name="LeftCurly">
<!-- Checks for placement of the left curly brace ('{'). -->
<property name="severity" value="warning"/>
</module>
<module name="RightCurly">
<property name="option" value="same"/>
<property name="severity" value="warning"/>
</module>
<!-- Checks for braces around if and else blocks -->
<module name="NeedBraces">
<property name="severity" value="warning"/>
<property name="tokens" value="LITERAL_IF, LITERAL_ELSE, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO"/>
</module>
<module name="UpperEll">
<!-- Checks that long constants are defined with an upper ell.-->
<property name="severity" value="error"/>
</module>
<module name="FallThrough">
<!-- Warn about falling through to the next case statement. Similar to
javac -Xlint:fallthrough, but the check is suppressed if a single-line comment
on the last non-blank line preceding the fallen-into case contains 'fall through' (or
some other variants which we don't publicized to promote consistency).
-->
<property name="reliefPattern"
value="fall through|Fall through|fallthru|Fallthru|falls through|Falls through|fallthrough|Fallthrough|No break|NO break|no break|continue on"/>
<property name="severity" value="error"/>
</module>
<!--
MODIFIERS CHECKS
-->
<!-- <module name="ModifierOrder">-->
<!-- &lt;!&ndash; Warn if modifier order is inconsistent with JLS3 8.1.1, 8.3.1, and-->
<!-- 8.4.3. The prescribed order is:-->
<!-- public, protected, private, abstract, static, final, transient, volatile,-->
<!-- synchronized, native, strictfp-->
<!-- &ndash;&gt;-->
<!-- </module>-->
<!--
WHITESPACE CHECKS
-->
<module name="WhitespaceAround">
<!-- Checks that various tokens are surrounded by whitespace.
This includes most binary operators and keywords followed
by regular or curly braces.
-->
<property name="tokens" value="ASSIGN, BAND, BAND_ASSIGN, BOR,
BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN,
EQUAL, GE, GT, LAND, LE, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE,
LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, LITERAL_RETURN,
LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS,
MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION,
SL, SL_ASSIGN, SR_ASSIGN, STAR, STAR_ASSIGN"/>
<property name="severity" value="error"/>
</module>
<module name="WhitespaceAfter">
<!-- Checks that commas, semicolons and typecasts are followed by
whitespace.
-->
<property name="tokens" value="COMMA, SEMI, TYPECAST"/>
</module>
<module name="NoWhitespaceAfter">
<!-- Checks that there is no whitespace after various unary operators.
Linebreaks are allowed.
-->
<property name="tokens" value="BNOT, DEC, DOT, INC, LNOT, UNARY_MINUS,
UNARY_PLUS"/>
<property name="allowLineBreaks" value="true"/>
<property name="severity" value="error"/>
</module>
<module name="NoWhitespaceBefore">
<!-- Checks that there is no whitespace before various unary operators.
Linebreaks are allowed.
-->
<property name="tokens" value="SEMI, DOT, POST_DEC, POST_INC"/>
<property name="allowLineBreaks" value="true"/>
<property name="severity" value="error"/>
</module>
<module name="ParenPad">
<!-- Checks that there is no whitespace before close parens or after
open parens.
-->
<property name="severity" value="warning"/>
</module>
</module>
</module>
<?xml version="1.0" encoding="UTF-8"?>
<checkstyle version="6.18">
</checkstyle>
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册