如何用java 5分钟实现一个最简单的mysql代理服务器

如题所述

如何用java 5分钟实现一个最简单的mysql代理服务器
首先,准备开发工具套件,我们并不会引入过多工具包,仅仅需要:
java8
vert.x 3
如果你是用maven做为项目管理工具,请将vert.x 3引入:

1
2
3
4
5

<dependency>

<groupId>io.vertx</groupId>

<artifactId>vertx-core</artifactId>

<version>3.3.2</version>

</dependency>

代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

package
com.maxleap.mysqlproxy;

import
io.vertx.core.AbstractVerticle;

import
io.vertx.core.Vertx;

import
io.vertx.core.logging.Logger;

import
io.vertx.core.logging.LoggerFactory;

import
io.vertx.core.net.NetClient;

import
io.vertx.core.net.NetServer;

import
io.vertx.core.net.NetSocket;

/**

*
@author sneaky

*
@since 1.0.0

*/

public
class
MysqlProxyServer
{

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

public
static
void
main(String[]
args)
{

Vertx.vertx().deployVerticle(new
MysqlProxyServerVerticle());

}

public
static
class
MysqlProxyServerVerticle
extends
AbstractVerticle
{

private
final
int
port
=
3306;

private
final
String
mysqlHost
=
"10.10.0.6";

@Override

public
void
start()
throws
Exception
{

NetServer
netServer
=
vertx.createNetServer();//创建代理服务器

NetClient
netClient
=
vertx.createNetClient();//创建连接mysql客户端

netServer.connectHandler(socket
->
netClient.connect(port,
mysqlHost,
result
->
{

//响应来自客户端的连接请求,成功之后,在建立一个与目标mysql服务器的连接

if
(result.succeeded())
{

//与目标mysql服务器成功连接连接之后,创造一个MysqlProxyConnection对象,并执行代理方法

new
MysqlProxyConnection(socket,
result.result()).proxy();
温馨提示:答案为网友推荐,仅供参考