Grain is a minimalist, component-based RPC framework that is flexible and suitable for progressive learning and can be integrated with any framework. At the same time includes (system universal multithreading model and message communication, many-to-many relationship distributed lock, HTTP framework based on Servlet, Websocket framework based on system universal multithreading model, support row level multithreading lock) and other components, according to the need to select components, do not kidnap developers.

The GRAIN Architecture diagram and its dependencies (dark colors are strongly recommended for core components)

Core Components


1. Grain-thread (System Universal multithreading model)

Introduction: Perfect abstraction of objective things, including: 1, active in the thread between the living things, into the action, leave the action, rotation training action (for example: people can switch between threads), 2, processing immediately destroyed non-living things, processing action (for example: all kinds of message packets can be destroyed after processing). 3, excellent multi-threaded rotation mechanism, queue mechanism (producer and consumer), the server has absolute control.

Usage scenarios: Grain-RPC, Grain-distributedLock, and Grain-ThreadWebSocket are all based on the common multithreading model of this system. Any business that requires multithreading can be used: MMORPG, instant messaging, etc.

Sample code:

1, start the example, create 10 threads, each thread 3 priority, each rotation training interval of 100 milliseconds, through ILog implementation of the object to print logs, lock 0 threads.

Asyncthreadmanager.init (100, 10, 3, 0, ILog implementation object); AsyncThreadManager.start();Copy the code

2. Add the living creatures to the queue of thread 1 and priority 1 (entry action will be triggered later, and rotation action will be continuously triggered later)

AsyncThreadManager. AddCycle (ICycle to realize the object of the class, 1, 1);Copy the code

3. Add the living creature to the exit queue of thread 1 and priority 1 (exit action will be triggered later)

AsyncThreadManager. RemoveCycle (ICycle to realize the object of the class, 1, 1);Copy the code

4. Add inanimate objects to the processing queue of thread 1 and Priority 1 (processing action will be triggered later, and the processing will be destroyed immediately after processing)

AsyncThreadManager. AddHandle (IHandle to realize the object of the class, 1, 1);Copy the code

Grain-threadmsg (System universal multithreading model and message communication).

Support message communication between system universal multithreaded model and system universal multithreaded model. You can configure messages, register messages, distribute messages, and callback messages.

Usage scenarios: scenarios that require a common multithreaded model for the system, generally requiring messaging. It can always be bound to grain-thread.

Sample code:

1, initialization, through ILog to achieve the object of the class to print logs

Msgmanager.init (true, Ilog log);Copy the code

Set all createUser handlers to thread 1, priority 1 (if not set)

ThreadMsgManager.addMapping("createuser", new int[] { 1, 1 });Copy the code

3, register concern about a message and the corresponding processing function (step 2 message set which thread, the corresponding processing function callback in the thread)

MsgManager. AddMsgListener (IMsgListener implementation class object);Copy the code

Send createUser with data 111 and extra data 222.

ThreadMsgManager.dispatchThreadMsg("createuser", 111, 222);Copy the code

Grain-rpc (RPC framework that supports many-to-many relationship, including RPC client and RPC server).

Introduction: RPC communication framework based on Mina network layer and Protobuf serialization is developed. Compared with layer 7 HTTP communication, layer 4 TCP communication message packet is smaller, transmission speed is faster, message packet processing queue, message packet and thread can be mapped and configured one by one, support many-to-many relationship, disconnection and reconnection, etc.

Application scenario: In the production environment, servers on the internal network communicate with each other.

Sample code:

1.RPC client (start class test.rpcclientTest. Java, directly start to connect to the following RPC server)

>>>>>>RPC client Demo

2.RPC server (start class test.rpcServertest. Java, directly start to accept the above RPC client connection request)

>>>>>>RPC server Demo

3. Example of obtaining data through RPC

Rpctestc.builder Builder = rpctestc.newBuilder (); Builder.setname (" Hello RPC server "); TcpPacket pt = new TcpPacket("TEST_RPC_C", builder.build()); TcpPacket ptReturn = waitlockManager. lock(session, pt);Copy the code

Grain-distributedlock (supports many-to-many distributed locks, including distributedlock clients and distributedlock servers).

Introduction: Decentralized, row-level locking (locking a single key value of a certain type). Different types do not affect each other, and different key values of the same type do not affect each other. Distributed blocking occurs only if both type and key are equal.

Note: If a server has assumed the role of distributed lock server, do not use that server to assume another role, as most threads on that server will block from time to time waiting for the lock client to release the lock.

Usage scenario: In a decentralized server cluster, this makes a lot of sense. Without relying on Mysql database, the atomicity of server cluster service can be guaranteed, the performance of server cluster can be greatly improved, and the wrong database submission can be reduced.

Sample code:

1, distributed lock (client start the class test. DistributedlockClientTest. Java, can be started directly connected distributed lock server below)

>>>>>> Distributed lock client Demo

2 lock, distributed server (start the class test. DistributedlockServerTest. Java, can directly start to accept the above distributed lock client connection requests)

>>>>>> Distributed lock server Demo

3. Example of distributed client acquiring lock and releasing lock

/ / type for the user, the key value of 111 lock int lockId = DistributedLockClient. GetLock (" 111 ", "user"); if (lockId == 0) { return; } / * * * * * * * * * * * to perform distributed lock business logic start * * * * * * * * * / / * * * * * * * * * * * to perform distributed lock business logic end * * * * * * * * * / / / release type for the user, Key value is 111 lock DistributedLockClient. UnLock (" 111 ", "user", lockId);Copy the code

Grain-thread Websocket (Websocket framework based on system common multithreading model)

Description: Websocket messages are not processed by the default Tomcat thread and are distributed to the system’s universal multithreaded model for queuing processing. More customizable, support webSocket message and thread ID one-to-one mapping, server absolute processing control.

Usage scenario: This framework can be used when a website needs long connection communication.

Sample code:

1, Websocket server (tomcat8.5 start can be used directly, direct access to the address, http://localhost:8080/grain-threadwebsocket-test/index.html, to establish the connection with the server)

>>>>>>Websocket server Demo

2. Processing service examples

public void onTestC(WsPacket wsPacket) throws IOException, EncodeException {TestC TestC = (TestC) wspacket.getData (); Tests.builder TestS = tests.newBuilder (); tests.setWsOpCode("tests"); Tests. setMsg(" Hello client, this is the server "); WsPacket pt = new WsPacket("tests", tests.build()); Session session = (session) wspacket.session; Session.getbasicremote ().sendobject (pt); }Copy the code

Grain-httpserver (Servlet based HTTP framework)

Introduction: a very lightweight servlet-based HTTP framework with only 1318 lines of code. Small stature, complete five zang organs, expandable. Support various request methods, support file and packet separation, support extended request filter, support extended request reply type.

Usage scenario: If you want to develop HTTP projects without Spring or Struts2, this framework is as lightweight as it can be (unless you want to use servlets directly).

Sample code:

1, the HTTP server (tomcat8.5 start can be used directly, direct access to the address http://localhost:8080/grain-httpserver-test/index.html, sending pure data request and send the file to carry the form)

>>>>>>HTTP server Demo

2. Examples of 6 return types (extensible)

// Return JSON public HttpPacket onTestC(HttpPacket HttpPacket) throws HttpException {GetTokenS.Builder Builder = GetTokenS.newBuilder(); builder.setHOpCode(httpPacket.gethOpCode()); builder.setTokenId("111111"); builder.setTokenExpireTime("222222"); HttpPacket packet = new HttpPacket(httpPacket.gethOpCode(), builder.build()); return packet; }Copy the code
Public ReplyFile onFileC(HttpPacket HttpPacket) throws HttpException {File File = new File("k_nearest_neighbors.png"); ReplyFile ReplyFile = new ReplyFile(file, "hello.png "); return replyFile; }Copy the code
Public ReplyImage onImageC(HttpPacket HttpPacket) throws HttpException {File File = new File("k_nearest_neighbors.png"); ReplyImage image = new ReplyImage(file); return image; }Copy the code
Public String onStringC(HttpPacket HttpPacket) throws HttpException {return "<html><head></head><body><h1>xxxxxxxxxxxx<h1></body></html>"; }Copy the code
Public ReplyString onReplyStringC(HttpPacket HttpPacket) throws HttpException {String STR = "<html><head></head><body><h1>xxxxxxxxxxxx<h1></body></html>"; ReplyString replyString = new ReplyString(str, "text/html"); return replyString; }Copy the code
// Throw a custom error, Public void onException(HttpPacket HttpPacket) throws HttpException {GetTokenS.Builder Builder = GetTokenS.newBuilder(); builder.setHOpCode("0"); builder.setTokenId("111111"); builder.setTokenExpireTime("222222"); throw new HttpException("0", builder.build()); }Copy the code

Grain-threadkeylock (multithreaded lock that supports row-level locking)

Description: support lock type of single key value and double key value of multi-thread lock, refined to row level lock, improve concurrency.

Note: single server architecture is valuable, cluster architecture is meaningless, use grain-distributedLock for cluster architecture.

Usage scenario: In single-server architectures, row-level locking can be supported without database dependency.

Sample code:

Initialize multithreaded locks of type TEST1 and TEST2. The maximum lock wait time is 2 minutes. Wake up and retry every 100 ms

Keylockmanager.init (new String[] {"TEST1", "TEST2"}, 120000, 100, ILog implementation object);Copy the code

2. Lock type TEST1 with key value 222 and call lockFunction with parameters STR and 111. (lockFunction not complete, block if type TEST1 is used at the same time, key 222)

Public String lockFunction(Object... Params) {} / / lock calls String STR = (String) KeyLockManager. LockMethod (" 222 ", "TEST1", (params) - > lockFunction (params), new Object[] { "str", 111 });Copy the code

Lock type TEST1 with keys 222 and 111, and call lockFunction with parameters STR and 111. (lockFunction not complete, block if type TEST1 is used at the same time, key 222 or 111)

Public String lockFunction(Object... Params) {} / / lock calls String STR = (String) KeyLockManager. LockMethod (" 111 ", "222", "TEST1". (params) -> lockFunction(params), new Object[] { "str", 111 });Copy the code

More Details

>>>>>>grain-thread- Details

>>>>>>grain-threadmsg- Details

>>>>>>grain-rpc- Details

>>>>>>grain-distributedlock- Details

>>>>>> grain-threadwebSocket – Details

>>>>>> grain-httpServer – Details

>>>>>> grain-ThreadKeylock – Details

>>>>>>grain-log- Details (not recommended alone)

>>>>>>grain-msg- Details (use grain-threadmsg directly is not recommended)

>>>>>>grain-tcp- Details (It is not recommended to use grain-rpc directly.)

>>>>>>grain-config- Details

>>>>>> grain-Reds – Details

>>>>>>grain-mongodb- Details

>>>>>>grain-mariadb- Details

>>>>>>grain-websocket- Details (grain-threadwebSocket is recommended instead of recommended)

>>>>>> grain-httpClient – Details

A version

ant
Copy the code

Recommended Environment:

Jdk-8u121 apache-tomcat-8.5.12 mariadb-10.1.22 centos-7-1611 mongodb-3.4.3 redis-2.8.19Copy the code

Grain address:

>>>>>>github

> > > > > > code cloud