当前位置:网站首页>Responsive MySQL of vertx
Responsive MySQL of vertx
2022-07-03 07:25:00 【Sleeping Empire】
Introduce
Vertx Response type mysql client , With simple API, Focus on scalability and low overhead , characteristic :
- Event driven
- Lightweight
- Built in database connection pool
- Prefabricated query cache
- Vernier support
- Query line stream operation
- RxJava api Support
- 0 Copy object conversion
- Complete data type support
- Stored procedure support
- TLS/SSL Support
- MySQL Utility commands support
- MySQL and MariaDB Support
- Rich character set support
- Unix domain socket Support
1. maven Project dependence
<dependencies>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-config-yaml</artifactId>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-mysql-client</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.lance.common</groupId>
<artifactId>vertx-common-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
2.YAML File configuration
server:
port: 8000
mysql:
host: 127.0.0.1
port: 3306
database: v_example
username: root
password: li123456
charset: utf8
collation: utf8_general_ci
maxSize: 30
reconnectAttempts: 3
reconnectInterval: 1000
poolName: v-pool
3. Start loading profile , And into the config In the middle
public class MysqlApplication {
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
ConfigRetriever retriever = readYaml(vertx);
retriever.getConfig(json -> {
try {
JsonObject object = json.result();
DbHelper dbHelper = new DbHelper(object.getJsonObject("mysql"), vertx);
dbHelper.afterPropertiesSet();
DeploymentOptions options = new DeploymentOptions().setConfig(object);
vertx.deployVerticle(MainApp.class.getName(), options);
} catch (Exception ex) {
log.error("===> Vertx start fail: ", ex);
}
});
}
/**
* read yaml config
*
* @param vertx vertx
* @return ConfigRetriever
*/
private static ConfigRetriever readYaml(Vertx vertx) {
ConfigStoreOptions store = new ConfigStoreOptions()
.setType("file")
.setFormat("yaml")
.setOptional(true)
.setConfig(new JsonObject().put("path", "application.yaml"));
return ConfigRetriever.create(vertx, new ConfigRetrieverOptions().addStore(store));
}
}
4.Mysql Connection pool configuration
public class DbHelper {
private final JsonObject object;
private final Vertx vertx;
private static MySQLPool mySqlPool;
/**
* Get the client
*
* @return MySQLPool
*/
public static MySQLPool client() {
return mySqlPool;
}
/**
* initialization mysql Connect
*/
public void afterPropertiesSet() {
ConfigProperties.MysqlProperties properties = object.mapTo(ConfigProperties.MysqlProperties.class);
MySQLConnectOptions connectOptions = new MySQLConnectOptions()
.setPort(properties.getPort())
.setHost(properties.getHost())
.setDatabase(properties.getDatabase())
.setUser(properties.getUsername())
.setPassword(properties.getPassword())
.setReconnectAttempts(properties.getReconnectAttempts())
.setReconnectInterval(properties.getReconnectInterval())
.setCharset(properties.getCharset())
.setCollation(properties.getCollation());
PoolOptions poolOptions = new PoolOptions()
.setMaxSize(properties.getMaxSize())
.setName(properties.getPoolName())
.setShared(true);
mySqlPool = MySQLPool.pool(vertx, connectOptions, poolOptions);
}
}
5. Connection pool database sql perform
public class UserService {
/**
* find list
*/
public void list(RoutingContext ctx) {
MySQLPool pool = DbHelper.client();
pool.query("select *From t_user").mapping(UserInfo.row2User()).execute(rs -> {
if (rs.succeeded()) {
RowSet<UserInfo> result = rs.result();
List<UserInfo> list = new ArrayList<>();
result.forEach(list::add);
ctx.json(R.data(list));
} else {
log.warn("Failure: ", rs.cause());
}
});
}
/**
* find one
*/
public void detail(RoutingContext ctx) {
String userId = ctx.pathParam("userId");
MySQLPool pool = DbHelper.client();
pool.preparedQuery("select *From t_user where user_id=?").mapping(UserInfo.row2User()).execute(Tuple.of(userId), rs -> {
if (rs.succeeded()) {
RowSet<UserInfo> result = rs.result();
if (result.size() > 0) {
ctx.json(R.data(result.iterator().next()));
return;
}
ctx.json(R.data(null));
} else {
log.warn("Failure: ", rs.cause());
}
});
}
/**
* add user info
*/
public void add(RoutingContext ctx) {
UserInfo user = ctx.getBodyAsJson().mapTo(UserInfo.class);
if (user == null) {
ctx.json(R.fail(" The parameter is empty. "));
return;
}
MySQLPool pool = DbHelper.client();
pool.preparedQuery("insert into t_user(username,password,age,status,create_time,update_time)value(?,?,?,1,now(),now())")
.execute(Tuple.of(user.getUsername(), user.getPassword(), user.getAge()), rs -> {
if (rs.succeeded()) {
ctx.json(R.success("success"));
} else {
log.warn("Failure: ", rs.cause());
ctx.json(R.fail("fail"));
}
});
}
/**
* update user
*/
public void update(RoutingContext ctx) {
UserInfo user = ctx.getBodyAsJson().mapTo(UserInfo.class);
if (user == null) {
ctx.json(R.fail(" The parameter is empty. "));
return;
}
MySQLPool pool = DbHelper.client();
pool.preparedQuery("update t_user set username=?,password=?,age=?,status=?,update_time=now() where user_id=?")
.execute(Tuple.of(user.getUsername(), user.getPassword(), user.getAge(), user.getStatus(), user.getUserId()), rs -> {
if (rs.succeeded()) {
ctx.json(R.success("success"));
} else {
log.warn("Failure: ", rs.cause());
ctx.json(R.fail("fail"));
}
});
}
/**
* delete one
*/
public void delete(RoutingContext ctx) {
String userId = ctx.pathParam("userId");
MySQLPool pool = DbHelper.client();
pool.preparedQuery("delete From t_user where user_id=?").execute(Tuple.of(userId), rs -> {
if (rs.succeeded()) {
ctx.json(R.data("success"));
} else {
log.warn("Failure: ", rs.cause());
ctx.json(R.fail("fail"));
}
});
}
}
6. Full address of the project
边栏推荐
- VMWare网络模式-桥接,Host-Only,NAT网络
- 【开发笔记】基于机智云4G转接板GC211的设备上云APP控制
- Le Seigneur des anneaux: l'anneau du pouvoir
- Spa single page application
- [solved] unknown error 1146
- Comparison of advantages and disadvantages between most complete SQL and NoSQL
- Lombok cooperates with @slf4j and logback to realize logging
- High concurrency memory pool
- Distributed transactions
- Common problems in io streams
猜你喜欢
Margin left: -100% understanding in the Grail layout
Topic | synchronous asynchronous
VMware network mode - bridge, host only, NAT network
Docker builds MySQL: the specified path of version 5.7 cannot be mounted.
[set theory] equivalence classes (concept of equivalence classes | examples of equivalence classes | properties of equivalence classes | quotient sets | examples of quotient sets)*
“百度杯”CTF比赛 2017 二月场,Web:爆破-1
深度学习参数初始化(一)Xavier初始化 含代码
Spa single page application
TreeMap
SecureCRT password to cancel session recording
随机推荐
【已解决】Unknown error 1146
Advanced API (multithreading 02)
"Baidu Cup" CTF game 2017 February, Web: blast-1
Introduction of buffer flow
Advanced API (use of file class)
Jeecg request URL signature
c语言指针的概念
Interfaces and related concepts
【开发笔记】基于机智云4G转接板GC211的设备上云APP控制
Hello world of vertx
Distributed ID
Le Seigneur des anneaux: l'anneau du pouvoir
萬卷書 - 價值投資者指南 [The Education of a Value Investor]
IPv4 address
Longest common prefix and
Advanced API (serialization & deserialization)
MySQL syntax (basic)
SQL create temporary table
URL programming
【最詳細】最新最全Redis面試大全(50道)