一、建立集群
首先 在C盘新建两个文件夹,data1、data2
在MongoDB 的bin目录下,分别打开三个命令提示符 ,用于Mongo启动和连接
第一个:
mongod.exe -dbpath C:\data1 --port 27017 --replSet rs1
第二个:
mongod.exe -dbpath C:\data2 --port 27018 --replSet rs1
第三个: 连接27017的Mongo,
mongo
rs.initiate()
rs.add("localhost:27018")
rs.status()
二、新建Spring 项目
依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
</dependencies>
配置: application.yml
spring:
data:
mongodb:
uri: mongodb://localhost:27017/test?replicaSet=rs1
实体:
@Data
@Document("people")
public class People {
private String name;
private String phone;
}
服务:
@Service
public class PeopleService {
@Autowired
MongoTemplate mongoTemplate;
public void add() {
People people = new People();
people.setName("111");
people.setPhone("222");
mongoTemplate.insert(people);
}
@Transactional(rollbackFor = Exception.class)
public void addError() {
People people = new People();
people.setName("111211111111");
people.setPhone("222311111111");
mongoTemplate.insert(people);
int i = 1 / 0;
System.out.println("i=======" + i);
}
}
事务配置:
@Configuration
public class MongoTransactionConfiguration {
@Bean
MongoTransactionManager mongoTransactionManager(MongoDbFactory factory) {
return new MongoTransactionManager(factory);
}
}
测试类:
@SpringBootTest
class DemoApplicationTests {
@Autowired
PeopleService peopleService;
@Test
void add() {
peopleService.add();
}
@Test
void addError() {
peopleService.addError();
}
}