Files
rikako-note/spring/spring data r2dbc/r2dbc.md
2025-08-21 19:41:23 +08:00

3.6 KiB
Raw Blame History

R2DBC

Getting Started

引入pom

在spring boot项目中如果要适配spring data r2dbc可以引入如下pom依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-r2dbc</artifactId>
        </dependency>

        <dependency>
            <groupId>io.asyncer</groupId>
            <artifactId>r2dbc-mysql</artifactId>
            <version>1.4.1</version>
        </dependency>

create pojo & create table

之后,可以创建如下实体:

public class Person {

	private final String id;
	private final String name;
	private final int age;

	public Person(String id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public String getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
}

创建table

CREATE TABLE person(
    id VARCHAR(255) PRIMARY KEY,
    name VARCHAR(255),
    age INT
);

声明ConnectionFactory

@Configuration
@Slf4j
public class ConnectionFactoryConf extends AbstractR2dbcConfiguration {
    @Bean
    public ConnectionFactory connectionFactory() {
//        ConnectionFactories.get("jdbc:mysql://localhost:3306/innodb_demo?useSSL=false&rewriteBatchedStatements=true")
//                .
        ConnectionFactoryOptions options = ConnectionFactoryOptions.builder()
                .option(ConnectionFactoryOptions.HOST, "localhost")
                .option(ConnectionFactoryOptions.PORT, 3306)
                .option(ConnectionFactoryOptions.DRIVER, "mysql")
                .option(ConnectionFactoryOptions.USER, "rw_all_db")
                .option(ConnectionFactoryOptions.PASSWORD, "ab19971025")
                .option(ConnectionFactoryOptions.DATABASE, "asahi_schedule")
                .build();
        ConnectionPoolConfiguration poolConf = ConnectionPoolConfiguration.builder()
                .connectionFactory(ConnectionFactories.get(options))
                .maxSize(10)
                .validationQuery("SELECT 1")
                .build();
        return new ConnectionPool(poolConf);
    }
}

在上述示例中Conf类继承了AbstractR2dbcConfiguration类相比于直接注入connectionFactory对象通过AbstractR2dbcConfiguration注册能够提供ExceptionTranslator将r2dbc中的异常翻译为DataAccessException。

通过R2dbcEntityTemplate操作数据库

通过entityTemplate操作数据库的示例如下

R2dbcEntityTemplate template = new R2dbcEntityTemplate(connectionFactory);

    template.getDatabaseClient().sql("CREATE TABLE person" +
        "(id VARCHAR(255) PRIMARY KEY," +
        "name VARCHAR(255)," +
        "age INT)")
      .fetch()
      .rowsUpdated()
      .as(StepVerifier::create)
      .expectNextCount(1)
      .verifyComplete();

    template.insert(Person.class)
      .using(new Person("joe", "Joe", 34))
      .as(StepVerifier::create)
      .expectNextCount(1)
      .verifyComplete();

    template.select(Person.class)
      .first()
      .doOnNext(it -> log.info(it))
      .as(StepVerifier::create)
      .expectNextCount(1)
      .verifyComplete();
  }

在上述示例中pojo到table的映射会自动生效并不需要额外的元数据。

Dialects

spring data R2DBC会使用Dialect来对特定数据库/driver的行为进行封装。