当前位置:网站首页>Vertx's responsive MySQL template
Vertx's responsive MySQL template
2022-07-03 07:25:00 【Sleeping Empire】
Introduce
Vertx Response type mysql client , be based on SQL Client Templates Template operation sql Script
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>io.vertx</groupId>
<artifactId>vertx-sql-client-templates</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 TemplateApplication {
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();
SqlTemplate.forQuery(pool, select(null))
.mapTo(UserInfo.class)
.execute(null)
.onSuccess(rs -> {
List<UserInfo> list = new ArrayList<>();
rs.forEach(list::add);
ctx.json(R.data(list));
}).onFailure(e -> {
log.warn("Failure: ", e);
ctx.json(R.fail("list fail"));
});
}
/**
* find one
*/
public void detail(RoutingContext ctx) {
MySQLPool pool = DbHelper.client();
SqlTemplate.forQuery(pool, select("where user_id=#{userId}"))
.mapTo(UserInfo.class)
.execute(Collections.singletonMap("userId", ctx.pathParam("userId")))
.onSuccess(result -> {
if (result.size() > 0) {
ctx.json(R.data(result.iterator().next()));
return;
}
ctx.json(R.data(null));
}).onFailure(e -> {
log.warn("Failure: ", e);
ctx.json(R.fail("detail fail"));
});
}
/**
* 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();
SqlTemplate.forUpdate(pool, "insert into t_user(username,password,age,status,create_time,update_time)value(#{username},#{password},#{age},1,now(),now())")
.mapFrom(UserInfo.class)
.execute(user)
.onSuccess(v -> ctx.json(R.success("save success")))
.onFailure(e -> {
log.warn("Failure: ", e);
ctx.json(R.fail("save fail"));
});
}
/**
* update user
*/
public void update(RoutingContext ctx) {
log.info("===>{}", ctx.getBodyAsJson());
UserInfo user = ctx.getBodyAsJson().mapTo(UserInfo.class);
if (user == null) {
ctx.json(R.fail(" The parameter is empty. "));
return;
}
MySQLPool pool = DbHelper.client();
SqlTemplate.forUpdate(pool, "update t_user set username=#{username},password=#{password},age=#{age},status=#{status},update_time=now() where user_id=#{userId}")
.mapFrom(UserInfo.class)
.execute(user)
.onSuccess(v -> ctx.json(R.success("update success")))
.onFailure(e -> {
log.warn("Failure: ", e);
ctx.json(R.fail("update fail"));
});
}
/**
* delete one
*/
public void delete(RoutingContext ctx) {
MySQLPool pool = DbHelper.client();
SqlTemplate.forUpdate(pool, "delete From t_user where user_id=#{userId}")
.execute(Collections.singletonMap("userId", ctx.pathParam("userId")))
.onSuccess(v -> ctx.json(R.success("delete success")))
.onFailure(e -> {
log.warn("Failure: ", e);
ctx.json(R.fail("delete fail"));
});
}
private String select(String where) {
String select = "SELECT user_id as userId, username,password,age,status,create_time as createTime,update_time as updateTime from t_user";
if (StringUtils.isNotBlank(where)) {
select += " " + where;
}
return select;
}
}
6. Full address of the project
边栏推荐
- IO stream system and FileReader, filewriter
- "Baidu Cup" CTF game 2017 February, Web: blast-1
- Circuit, packet and message exchange
- 10 000 volumes - Guide de l'investisseur en valeur [l'éducation d'un investisseur en valeur]
- Docker builds MySQL: the specified path of version 5.7 cannot be mounted.
- Warehouse database fields_ Summary of SQL problems in kingbase8 migration of Jincang database
- LeetCode
- Jeecg menu path display problem
- 深度学习参数初始化(一)Xavier初始化 含代码
- Dora (discover offer request recognition) process of obtaining IP address
猜你喜欢

Basic components and intermediate components

High concurrency memory pool

Docker builds MySQL: the specified path of version 5.7 cannot be mounted.

为什么说数据服务化是下一代数据中台的方向?
![[solved] sqlexception: invalid value for getint() - 'Tian Peng‘](/img/bf/f6310304d58d964b3d09a9d011ddb5.png)
[solved] sqlexception: invalid value for getint() - 'Tian Peng‘

Basic knowledge about SQL database

4279. 笛卡尔树

Comparison of advantages and disadvantages between most complete SQL and NoSQL

不出网上线CS的各种姿势

3311. Longest arithmetic
随机推荐
Common methods of file class
4279. Cartesian tree
Comparison of advantages and disadvantages between most complete SQL and NoSQL
IPv4 address
[set theory] order relation (partial order relation | partial order set | example of partial order set)
Interview questions about producers and consumers (important)
树莓派更新工具链
OSI knowledge sorting
Deep learning parameter initialization (I) Xavier initialization with code
论文学习——鄱阳湖星子站水位时间序列相似度研究
SQL create temporary table
SharePoint modification usage analysis report is more than 30 days
[most detailed] latest and complete redis interview book (50)
Common problems in io streams
7.2 brush two questions
VMWare网络模式-桥接,Host-Only,NAT网络
Margin left: -100% understanding in the Grail layout
Why is data service the direction of the next generation data center?
Beginners use Minio
Advanced API (multithreading 02)