Recently I was learning r2dbc and encountered a problem. In order to test transactions in r2dbc, I wrote a small test project. sample code github
You can see the correct code on the master branch and the wrong code on the zd/transactional-test branch
First of all, we have a mysql table like this:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
`username` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'username',
`password` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'password',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'crete time',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
When the code is as follows, the annotation @Transactionl works well
1.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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>webflux-transactional</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>14</maven.compiler.source>
<maven.compiler.target>14</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-pool</artifactId>
<version>0.8.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.5</version>
</dependency>
<dependency>
<groupId>com.github.jasync-sql</groupId>
<artifactId>jasync-r2dbc-mysql</artifactId>
<version>1.1.6</version>
<exclusions>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-transport</artifactId>
</exclusion>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-handler</artifactId>
</exclusion>
<exclusion>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.4.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>3.4.4</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>3.4.4</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
- application.yaml
spring:
r2dbc:
url: r2dbc:pool:mysql://127.0.0.1:3306/webflux-r2dbc # r2dbc:mysql://127.0.0.1:3306/demo
username: root
password: 123456
pool:
initial-size: 5
max-size: 500
max-idle-time: 30m
validation-query: SELECT 1
server:
port: 8081
- DemoApplication
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- entity class
@Table(value = "users")
public class User {
@Id
private Integer id;
private String username;
private String password;
//omit getter setter
}
- UserRepository:
public interface UserRepository extends ReactiveCrudRepository<User, Integer> {
}
- UserService
@Service
public class UserService {
private final static Logger LOGGER = LoggerFactory.getLogger(UserService.class);
@Resource
R2dbcEntityTemplate r2dbcEntityTemplate;
@Transactional(rollbackFor = Exception.class)
public Mono<Integer> add1(User queryUser) {
return this.r2dbcEntityTemplate.insert(User.class)
.using(queryUser)
.doOnSuccess(user -> {
if (!user.getUsername().contains("exception")) {
LOGGER.info("=====================add normal=================");
} else {
LOGGER.error("=====================add exception=================");
throw new RuntimeException("add1 exception test............");
}
})
.map(User::getId);
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* test Transactional
* @param user
* @return
*/
@PostMapping("/add1")
public Mono<Integer> add1(@RequestBody User user){
return userService.add1(user);
}
}
- start test
When I execute the following request in intellij idea, as expected, an exception is thrown, and no record is inserted into the database.
POST http://localhost:8081/user/add1
Cache-Control: no-cache
Content-Type: application/json; charset=UTF-8
{
"username": "1exception11",
"password": "123456"
}
When I execute the following request in intellij idea, as expected, this record is inserted into the database.
POST http://localhost:8081/user/add1
Cache-Control: no-cache
Content-Type: application/json; charset=UTF-8
{
"username": "111",
"password": "123456"
}
- The above code is the correct step, and it is the last version I debugged successfully. The following code is what I used at the beginning, but the result is not the same as I expected.
On the basis of the above code, add a class:
@Configuration
@EnableTransactionManagement
public class DatabaseConfiguration extends AbstractR2dbcConfiguration {
@NotNull
@Override
public ConnectionFactory connectionFactory() {
String url = "mysql://root:123456@127.0.0.1:3306/webflux-r2dbc";
return new JasyncConnectionFactory(new MySQLConnectionFactory(URLParser.INSTANCE.parseOrDie(url, StandardCharsets.UTF_8)));
}
@Bean
public ReactiveTransactionManager transactionManager() throws URISyntaxException {
return new R2dbcTransactionManager(this.connectionFactory());
}
}
and modify UserService.java -add method add2()
@Service
public class UserService {
private final static Logger LOGGER = LoggerFactory.getLogger(UserService.class);
private final static String EXCEPTION = "exception";
@Resource
R2dbcEntityTemplate r2dbcEntityTemplate;
@Resource
UserRepository userRepository;
@Transactional(rollbackFor = Exception.class)
public Mono<Integer> add1(User queryUser) {
return this.r2dbcEntityTemplate.insert(User.class)
.using(queryUser)
.doOnSuccess(user -> {
if (!user.getUsername().contains(EXCEPTION)) {
LOGGER.info("=====================add normal=================");
} else {
LOGGER.error("=====================add exception=================");
throw new RuntimeException("add1 exception test............");
}
})
.map(User::getId);
}
@Transactional(rollbackFor = Exception.class)
public Mono<Integer> add2(User queryUser) {
return userRepository.save(queryUser).flatMap((Function<User, Mono<Integer>>) user -> {
if (user.getUsername().contains(EXCEPTION)) {
LOGGER.error("=====================add2 exception=================");
throw new RuntimeException("test exception...");
}
return Mono.just(user.getId());
});
}
}
and modify UserController.java -add method add2()
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* transaction work
* @param user
* @return
*/
@PostMapping("/add1")
public Mono<Integer> add1(@RequestBody User user){
return userService.add1(user);
}
/**
* transaction not ork
* @param user
* @return
*/
@PostMapping("/add2")
public Mono<Integer> add2(@RequestBody User user){
return userService.add2(user);
}
}
Test:
When I execute the following request in intellij idea, as expected, this record is inserted into the database.
POST http://localhost:8081/user/add1
Cache-Control: no-cache
Content-Type: application/json; charset=UTF-8
{
"username": "222",
"password": "123456"
}
When I execute the following request in intellij idea, an exception is thrown, and this record is inserted into the database.
POST http://localhost:8081/user/add1
Cache-Control: no-cache
Content-Type: application/json; charset=UTF-8
{
"username": "222exception",
"password": "123456"
}
Why does this happen, can anyone explain it, thank you very much.