随笔 - 836  文章 - 1 评论 - 40 阅读 - 102万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

原文:https://www.cnblogs.com/vettel0329/p/10778931.html

 

mongoDB单个实例不支持事务,副本集才支持事务

  • 1.准备好docker
  • 2.Spring boot 版本为2.1.1.RELEASE及以上

首先以主从模式安装mongodb 4.0.0以上的数据库实例,使用以下docker命令安装:(最新版不支持这种模式,必须是副本及模式,如果简单测试,可以使用)  

副本集搭建:https://www.cnblogs.com/lshan/p/12011980.html

docker run --privileged=true -p 10011:27017 -v $PWD/db1:/data/db -d --name template-db1 mongo:4.0.0 --replSet "templateRs0" --bind_ip_all 

docker run --privileged=true -p 10012:27017 -v $PWD/db2:/data/db -d --name template-db2 mongo:4.0.0 --replSet "templateRs0" --bind_ip_all 


原文链接:https://blog.csdn.net/quanmaoluo5461/article/details/84880850

然后连接到一个数据库实例以以下脚本初始化主节点:

rs.initiate( {
   _id : "templateRs0",
   members: [
      { _id: 0, host: "172.16.2.87:10011" },
      { _id: 1, host: "172.16.2.87:10012" },
   ]
})

rs.status()

 

依赖:

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

 

创建配置类,开启事务

复制代码
@Configuration
public class TransactionConfig {

    @Bean
    MongoTransactionManager transactionManager(MongoDbFactory factory){
        return new MongoTransactionManager(factory);
    }

}
复制代码

 

 

开启事务:

复制代码
@Service
public class UserService {

    @Resource
    MongoTemplate mongotemplate;

    public List<User> getAllUser(){
        return mongotemplate.findAll(User.class);
    }

    @Transactional
    public boolean addUser(User user, UserInfo userInfo){
        user.setUserInfo(userInfo);
        mongotemplate.save(userInfo);
//        int a = 1/0;    //事务测试代码
        mongotemplate.save(user);
        return true;
    }

}
复制代码

 

注:以上为MongoTemplate方式,MongoTemplate和MongoRepository方式都与Spring整合SpringDataMongoDB相同

 

posted on   lshan  阅读(2600)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示