iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >r2dbc在Spring webFlux中怎么使用
  • 383
分享到

r2dbc在Spring webFlux中怎么使用

2023-06-29 03:06:37 383人浏览 八月长安
摘要

这篇文章主要介绍“r2dbc在spring WEBFlux中怎么使用”,在日常操作中,相信很多人在r2dbc在Spring webFlux中怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”r2dbc在S

这篇文章主要介绍“r2dbc在spring WEBFlux中怎么使用”,在日常操作中,相信很多人在r2dbc在Spring webFlux中怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”r2dbc在Spring webFlux中怎么使用”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

r2dbc

Reactor还有基于其之上的Spring WebFlux框架。包括vert.x,rxjava等等reactive技术。我们实际上在应用层已经有很多优秀的响应式处理框架。

但是有一个问题就是所有的框架都需要获取底层的数据,而基本上关系型数据库的底层读写都还是同步的。

为了解决这个问题,出现了两个标准,一个是oracle提出的 ADBC (Asynchronous Database Access api),另一个就是Pivotal提出的R2DBC (Reactive Relational Database Connectivity)。

R2DBC是基于Reactive Streams标准来设计的。通过使用R2DBC,你可以使用reactive API来操作数据。

同时R2DBC只是一个开放的标准,而各个具体的数据库连接实现,需要实现这个标准。

工程依赖

以下是 pom.xml清单

<?xml version="1.0" encoding="UTF-8"?><project xmlns="Http://Maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>3.0.0-M1</version>        <relativePath/> <!-- lookup parent from repository -->    </parent>    <groupId>wang.datahub</groupId>    <artifactId>SpringBoot3Demo</artifactId>    <version>0.0.1-SNAPSHOT</version>    <name>springboot3demo</name>    <description>Demo project for Spring Boot</description>    <properties>        <java.version>17</java.version>    </properties>    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-r2dbc</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-redis-reactive</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-rest</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-groovy-templates</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-hateoas</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-webflux</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-configuration-processor</artifactId>            <optional>true</optional>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-devtools</artifactId>        </dependency>        <dependency>            <groupId>io.r2dbc</groupId>            <artifactId>r2dbc-h3</artifactId>        </dependency>        <dependency>            <groupId>com.h3database</groupId>            <artifactId>h3</artifactId>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>Mysql-connector-java</artifactId>            <scope>runtime</scope>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>        <dependency>            <groupId>io.projectreactor</groupId>            <artifactId>reactor-test</artifactId>            <scope>test</scope>        </dependency>        <dependency>            <groupId>io.projectreactor</groupId>            <artifactId>reactor-test</artifactId><!--            <version>3.4.14</version>--><!--            <scope>compile</scope>-->        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build>    <repositories>        <repository>            <id>spring-milestones</id>            <name>Spring Milestones</name>            <url>https://repo.spring.io/milestone</url>            <snapshots>                <enabled>false</enabled>            </snapshots>        </repository>        <repository>            <id>spring-snapshots</id>            <name>Spring Snapshots</name>            <url>https://repo.spring.io/snapshot</url>            <releases>                <enabled>false</enabled>            </releases>        </repository>    </repositories>    <pluginRepositories>        <pluginRepository>            <id>spring-milestones</id>            <name>Spring Milestones</name>            <url>https://repo.spring.io/milestone</url>            <snapshots>                <enabled>false</enabled>            </snapshots>        </pluginRepository>        <pluginRepository>            <id>spring-snapshots</id>            <name>Spring Snapshots</name>            <url>https://repo.spring.io/snapshot</url>            <releases>                <enabled>false</enabled>            </releases>        </pluginRepository>    </pluginRepositories></project>

配置文件

这里我们只配置了r2dbc链接信息

配置类

用于配置默认链接,创建初始化数据

package wang.datahub.springboot3demo.config;import io.Netty.util.internal.StringUtil;import io.r2dbc.spi.ConnectionFactories;import io.r2dbc.spi.ConnectionFactory;import io.r2dbc.spi.ConnectionFactoryOptions;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import reactor.core.publisher.Flux;import static io.r2dbc.spi.ConnectionFactoryOptions.*;@Configuration@ConfigurationProperties(prefix = "r2dbc")public class DBConfig {    private String url;    private String user;    private String passWord;    public String getUrl() {        return url;    }    public void setUrl(String url) {        this.url = url;    }    public String getUser() {        return user;    }    public void setUser(String user) {        this.user = user;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    @Bean    public ConnectionFactory connectionFactory() {        System.out.println("url ==> "+url);        ConnectionFactoryOptions baseOptions = ConnectionFactoryOptions.parse(url);        ConnectionFactoryOptions.Builder ob = ConnectionFactoryOptions.builder().from(baseOptions);        if (!StringUtil.isNullOrEmpty(user)) {            ob = ob.option(USER, user);        }        if (!StringUtil.isNullOrEmpty(password)) {            ob = ob.option(PASSWORD, password);        }        return ConnectionFactories.get(ob.build());    }    @Bean    public CommandLineRunner initDatabase(ConnectionFactory cf) {        return (args) ->                Flux.from(cf.create())                        .flatMap(c ->                                Flux.from(c.createBatch()                                                .add("drop table if exists Users")                                                .add("create table Users(" +                                                        "id IDENTITY(1,1)," +                                                        "firstname varchar(80) not null," +                                                        "lastname varchar(80) not null)")                                                .add("insert into Users(firstname,lastname)" +                                                        "values('Jacky','Li')")                                                .add("insert into Users(firstname,lastname)" +                                                        "values('Doudou','Li')")                                                .add("insert into Users(firstname,lastname)" +                                                        "values('Maimai','Li')")                                                .execute())                                        .doFinally((st) -> c.close())                        )                        .log()                        .blockLast();    }}

bean

创建用户bean

package wang.datahub.springboot3demo.bean;import org.springframework.data.annotation.Id;public class Users {    @Id    private Long id;    private String firstname;    private String lastname;    public Users(){    }    public Users(Long id, String firstname, String lastname) {        this.id = id;        this.firstname = firstname;        this.lastname = lastname;    }    public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }    public String getFirstname() {        return firstname;    }    public void setFirstname(String firstname) {        this.firstname = firstname;    }    public String getLastname() {        return lastname;    }    public void setLastname(String lastname) {        this.lastname = lastname;    }    @Override    public String toString() {        return "User{" +                "id=" + id +                ", firstname='" + firstname + '\'' +                ", lastname='" + lastname + '\'' +                '}';    }}

DAO

dao代码清单如下,包含查询列表、按id查询,以及创建用户等操作

package wang.datahub.springboot3demo.dao;import io.r2dbc.spi.Connection;import io.r2dbc.spi.ConnectionFactory;import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;import org.springframework.data.relational.core.query.Query;import org.springframework.stereotype.Component;import reactor.core.publisher.Flux;import reactor.core.publisher.Mono;import wang.datahub.springboot3demo.bean.Users;import static org.springframework.data.r2dbc.query.Criteria.where;import static org.springframework.data.relational.core.query.Query.query;@Componentpublic class UsersDao {    private ConnectionFactory connectionFactory;    private R2dbcEntityTemplate template;    public UsersDao(ConnectionFactory connectionFactory) {        this.connectionFactory = connectionFactory;        this.template = new R2dbcEntityTemplate(connectionFactory);    }    public Mono<Users> findById(long id) {        return this.template.selectOne(query(where("id").is(id)),Users.class);//        return Mono.from(connectionFactory.create())//                .flatMap(c -> Mono.from(c.createStatement("select id,firstname,lastname from Users where id = $1")//                                .bind("$1", id)//                                .execute())//                        .doFinally((st) -> close(c)))//                .map(result -> result.map((row, meta) ->//                        new Users(row.get("id", Long.class),//                                row.get("firstname", String.class),//                                row.get("lastname", String.class))))//                .flatMap( p -> Mono.from(p));    }    public Flux<Users> findAll() {        return this.template.select(Users.class).all();//        return Mono.from(connectionFactory.create())//                .flatMap((c) -> Mono.from(c.createStatement("select id,firstname,lastname from users")//                                .execute())//                        .doFinally((st) -> close(c)))//                .flatMapMany(result -> Flux.from(result.map((row, meta) -> {//                    Users acc = new Users();//                    acc.setId(row.get("id", Long.class));//                    acc.setFirstname(row.get("firstname", String.class));//                    acc.setLastname(row.get("lastname", String.class));//                    return acc;//                })));    }    public Mono<Users> createAccount(Users account) {        return Mono.from(connectionFactory.create())                .flatMap(c -> Mono.from(c.beginTransaction())                        .then(Mono.from(c.createStatement("insert into Users(firstname,lastname) values($1,$2)")                                .bind("$1", account.getFirstname())                                .bind("$2", account.getLastname())                                .returnGeneratedValues("id")                                .execute()))                        .map(result -> result.map((row, meta) ->                                new Users(row.get("id", Long.class),                                        account.getFirstname(),                                        account.getLastname())))                        .flatMap(pub -> Mono.from(pub))                        .delayUntil(r -> c.commitTransaction())                        .doFinally((st) -> c.close()));    }    private <T> Mono<T> close(Connection connection) {        return Mono.from(connection.close())                .then(Mono.empty());    }}

controller

controller代码清单如下,包含了查询列表、按id查询,以及创建用户等操作

package wang.datahub.springboot3demo.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;import reactor.core.publisher.Flux;import reactor.core.publisher.Mono;import wang.datahub.springboot3demo.bean.Users;import wang.datahub.springboot3demo.dao.UsersDao;@RestControllerpublic class UsersController {    @Autowired    private final UsersDao usersDao;    public UsersController(UsersDao usersDao) {        this.usersDao = usersDao;    }    @GetMapping("/users/{id}")    public Mono<ResponseEntity<Users>> getUsers(@PathVariable("id") Long id) {        return usersDao.findById(id)                .map(acc -> new ResponseEntity<>(acc, HttpStatus.OK))                .switchIfEmpty(Mono.just(new ResponseEntity<>(null, HttpStatus.NOT_FOUND)));    }    @GetMapping("/users")    public Flux<Users> getAllAccounts() {        return usersDao.findAll();    }    @PostMapping("/createUser")    public Mono<ResponseEntity<Users>> createUser(@RequestBody Users user) {        return usersDao.createAccount(user)                .map(acc -> new ResponseEntity<>(acc, HttpStatus.CREATED))                .log();    }}

启动类清单:

package wang.datahub.springboot3demo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.context.properties.EnableConfigurationProperties;import wang.datahub.springboot3demo.config.DBConfig;@SpringBootApplication@EnableConfigurationProperties(DBConfig.class)public class WebFluxR2dbcApp {    public static void main(String[] args) {        SpringApplication.run(WebFluxR2dbcApp.class, args);    }}

到此,关于“r2dbc在Spring webFlux中怎么使用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程网网站,小编会继续努力为大家带来更多实用的文章!

--结束END--

本文标题: r2dbc在Spring webFlux中怎么使用

本文链接: https://www.lsjlt.com/news/322323.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • r2dbc在Spring webFlux中怎么使用
    这篇文章主要介绍“r2dbc在Spring webFlux中怎么使用”,在日常操作中,相信很多人在r2dbc在Spring webFlux中怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”r2dbc在S...
    99+
    2023-06-29
  • 如何在Spring Boot中使用Webflux
    这篇文章主要介绍“如何在Spring Boot中使用Webflux”,在日常操作中,相信很多人在如何在Spring Boot中使用Webflux问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何在Spring...
    99+
    2023-06-02
  • Spring WebFlux的使用指南
    目录Spring-WebFlux框架 依赖项 响应式应用 响应式RestController 单一资源 集合资源 反应式Web客户端 检索单个资源 检索集合资源 Spring Web...
    99+
    2024-04-02
  • 如何正确的使用Spring WebFlux
    如何正确的使用Spring WebFlux?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。Spring-WebFlux框架Spring WebFlux在内部使用Project R...
    99+
    2023-06-14
  • FactoryBean怎么在spring中使用
    FactoryBean怎么在spring中使用?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。从SessionFactory说起:在使用SSH集成开发的时候,我们有时候会在app...
    99+
    2023-05-30
    spring factorybean
  • Properties怎么在Spring中使用
    Properties怎么在Spring中使用?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。1. 在 xml 配置文件中使用即自动替换 ${} 里面的值。<bean&nbs...
    99+
    2023-05-30
  • Admin 怎么在Spring Boot中使用
    本篇文章为大家展示了Admin 怎么在Spring Boot中使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。一、前言Spring Boot Admin 用于监控基于 Spring Boot 的应...
    99+
    2023-05-31
    springboot mi admin
  • 怎么在Spring Boot中使用MQTT
    这篇文章给大家分享的是有关怎么在Spring Boot中使用MQTT的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。为什么选择MQTTMQTT的定义相信很多人都能讲的头头是道,本文章也不讨论什么高大上的东西,旨在用...
    99+
    2023-06-14
  • 怎么在Spring Boot中使用MyBatis
    这篇文章将为大家详细讲解有关怎么在Spring Boot中使用MyBatis,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。orm框架的本质是简化编程中操作数据库的编码,发展到现在基本上就剩两...
    99+
    2023-05-31
    springboot mybatis
  • 怎么在java中使用Spring框架
    怎么在java中使用Spring框架?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。Java是什么Java是一门面向对象编程语言,可以编写桌面应用程序、Web应用程序、分布式系统...
    99+
    2023-06-14
  • Kafka和Storm怎么在Spring boot中使用
    这篇文章给大家介绍Kafka和Storm怎么在Spring boot中使用,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。使用工具及环境配置 java 版本jdk-1.8 编译工具使用IDEA-2017 maven作为项...
    99+
    2023-05-30
  • @Around注解怎么在Spring AOP中使用
    这期内容当中小编将会给大家带来有关@Around注解怎么在Spring AOP中使用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。@Around注解可以用来在调用一个具体方法前和调用后来完成一些具体的任务...
    99+
    2023-06-06
  • PropertySource注解怎么在Spring boot中使用
    本篇文章给大家分享的是有关PropertySource注解怎么在Spring boot中使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。1.1. PropertySource...
    99+
    2023-05-30
    springboot propertysource
  • http请求怎么在spring boot中使用
    今天就跟大家聊聊有关http请求怎么在spring boot中使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。首先是经过封装:一:初始化httpclientprivate ...
    99+
    2023-05-30
    springboot http
  • 在Spring中使用Quartz
    在Spring中使用Quartz,需要进行以下步骤:1. 添加依赖:在项目的pom.xml文件中添加Quartz的依赖。```xml...
    99+
    2023-09-15
    Spring
  • Spring Boot中怎么使用Spring MVC
    本篇内容主要讲解“Spring Boot中怎么使用Spring MVC”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Spring Boot中怎么使用Spring&n...
    99+
    2023-07-06
  • 怎么在Spring Boot中使用MongoDB数据库
    这篇文章给大家介绍怎么在Spring Boot中使用MongoDB数据库,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。MongoDB简介MongoDB是一个基于分布式文件存储的数据库,...
    99+
    2024-04-02
  • 怎么使用Spring integration在Springboot中集成Mqtt
    今天小编给大家分享一下怎么使用Spring integration在Springboot中集成Mqtt的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有...
    99+
    2023-07-05
  • spring @Primary-在spring中的使用方式
    spring @Primary在spring的使用 在spring 中使用注解,常使用@Autowired, 默认是根据类型Type来自动注入的。但有些特殊情况,对同一个接口,可能会...
    99+
    2024-04-02
  • spring中hibernate怎么使用
    本篇内容主要讲解“spring中hibernate怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“spring中hibernate怎么使用”吧!  首先需要配置数据源,通常我们有两种方式获...
    99+
    2023-06-03
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作