Spring Boot 2反应性JDBC

时间:2019-06-23 07:21:42

标签: spring-boot reactive-programming

我使用Spring Boot 2.2并尝试配置反应性jdbc。

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

数据源配置

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Connection url for the database
spring.datasource.url = jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
# Username and password
spring.datasource.username = root
spring.datasource.password = root

spring.datasource.hikari.connection-test-query=select 1
spring.datasource.hikari.connectionTimeout=30000
spring.datasource.hikari.idleTimeout=600000
spring.datasource.hikari.maxLifetime=1800000
spring.datasource.hikari.maximum-pool-size = 10

DataConfiguration,

@Configuration
public class DataConfiguration {

    @Value("${spring.datasource.hikari.maximum-pool-size:100}")
    private int connectionPoolSize;

    @Bean
    public Scheduler jdbcScheduler() {
        return Schedulers.fromExecutor(Executors.newFixedThreadPool(connectionPoolSize));
    }

    @Bean
    public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {
        return new TransactionTemplate(transactionManager);
    }
}

我在网上看到了上面的示例,不确定在这里为什么需要TransactionTemplate bean。

DataManager,

@Component
public class UserDataManager {

    String sql = "SELECT ID FROM table WHERE ID=?";

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    @Qualifier("jdbcScheduler")
    Scheduler jdbcScheduler;

    public Mono<Optional<User>> findById(Long id) {
        return asyncCallable(() -> Optional.of(jdbcTemplate.queryForObject (sql, new Object[] { id }, new UserRowMapper())));
    }

    protected <S> Mono<S> asyncCallable(Callable<S> callable) {
        return Mono.fromCallable(callable).subscribeOn(Schedulers.parallel()).publishOn(jdbcScheduler);
    }

    protected <S> Flux<S> asyncIterable(Iterable<S> iterable) {
        return Flux.fromIterable(iterable).subscribeOn(Schedulers.parallel()).publishOn(jdbcScheduler);
    }

}

只想确认这是正确的还是需要微调的? 我们需要TransactionTemplate bean吗?

谢谢

0 个答案:

没有答案