前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[Hibernate事务管理基于Sessi...]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Hibernate
...中非常重要的工具——Hibernate。Hibernate,这可真是个牛哄哄的对象关系映射框架,它就像开发者与数据库之间的超级小助手,让大伙儿能够更加轻松愉快地和数据库打交道,处理数据啥的简直不要太方便! 今天我们要讲的主题是SessionFactory的初始化与作用。这可真是咱们不能忽视的关键一步呀,它可是会直接影响到我们程序跑得顺不顺畅,数据安不安全的大问题嘞!那么,我们一起来学习一下吧! 二、什么是SessionFactory 首先,我们需要明确一点:SessionFactory是一个工厂类,用于创建Session对象。Session是Hibernate的核心,它负责处理所有的持久化操作。SessionFactory,你就想象成一个超级能干的制造小能手,它的任务就是帮咱们精心打造出一个个我们需要的Session对象。 三、SessionFactory初始化过程 接下来,我们就来详细讲解一下SessionFactory的初始化过程。 1. 配置文件加载 我们先看第一步,配置文件加载。在这里,我们主要指的是hibernate.cfg.xml这个文件。这个文件里头记录了一些Hibernate的基础配置内容,就好比是数据库连接的小秘籍,还有实体类映射的说明书啥的。 2. 创建SessionFactory实例 有了配置文件之后,我们就可以开始创建SessionFactory实例了。这个过程是通过调用Configuration类的configure()方法实现的。 java Configuration configuration = new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); 3. 初始化SessionFactory 最后一步就是初始化SessionFactory了。这一步骤的重点,就像是给Hibernate来一场赛前热身,做些“幕后工作”,像是把SQL语句好好捯饬捯饬、让它跑得更快更顺溜,还有就是调整缓存设置,让数据存取效率嗖嗖地提升。 java sessionFactory.openSession(); 四、SessionFactory的作用 了解了SessionFactory的初始化过程后,我们再来谈谈它的作用。 1. Session对象的生成 就像前面提到的那样,SessionFactory是一个工厂类,它的主要任务就是生成Session对象。我们可以利用SessionFactory来创建多个Session对象,每个Session对象都可以用来进行持久化操作。 2. 事务管理 SessionFactory还可以帮助我们管理事务。在Hibernate中,事务是由Session对象管理的。如果你想在一个操作流程里搞定多个要保存的东西,其实特别简单,你只需要在一个Session对象里面挨个调用对应的方法就OK啦,就像咱们平时在电脑上打开一个窗口,然后在这个窗口里完成一系列操作一样方便。 3. 数据库优化 除了上述功能外,SessionFactory还有一个很重要的作用就是进行数据库优化。例如,它可以预编译SQL语句,从而提高执行速度;它还可以设置缓存策略,避免频繁从数据库中读取数据。 五、总结 以上就是关于SessionFactory的初始化过程以及作用的详细介绍。总的来说,SessionFactory在Hibernate里扮演着核心角色,对我们这些开发者来说,掌握它的一些基本操作和原理,那可是必不可少的! 希望通过这篇文章,能让你对SessionFactory有一个更深入的理解。如果你还有其他问题,欢迎随时留言,我会尽力回答你的。 六、致谢 最后,我要感谢每一位读者朋友的支持和鼓励。大家伙儿对我的支持和热爱,就像火把一样点燃了我前进的动力!我会倍加努力,不断钻研,给大家带来更多新鲜、有趣、接地气的技术分享,让咱们一起在技术的海洋里畅游吧! 谢谢大家,期待下次再见! Best regards, [你的名字]
2023-07-29 23:00:44
491
半夏微凉-t
Hibernate
Hibernate ORM 数据库持久层工具篇 一、Introduction ORM(Object-Relational Mapping)是将对象与关系数据之间进行映射的技术。这是一种编程招数,让程序员们能够像操作对象一样轻松玩转数据库,运用的就是面向对象的编程思维。 Hibernate 是一个开源的 Java 库,它是目前最流行的 ORM 框架之一。它的主要目标是使开发人员能够更容易地管理对象状态和关系。 二、Hibernate 的基本概念 Hibernate 中的核心概念是 Session。在Hibernate的世界里,Session可真是个大忙人,它实际上是个接口,但你可别小瞧这个接口,人家可是掌管着数据库操作的“大管家”。无论是创建、读取、更新还是删除(也就是我们常说的CRUD操作),还是处理那些复杂的事务问题,全都在它的职责范围内,可以说是数据库操作的核心工具了。 此外,Hibernate 还提供了几个重要的对象:SessionFactory、Transaction 和 Query。 SessionFactory 是用于创建 Session 的工厂类,我们可以通过调用它的 openSession() 方法来打开一个新的 Session。 Transaction 是 Hibernate 提供的一种事务处理机制,我们可以使用 Transaction 来管理多个 SQL 语句的操作,保证操作的一致性和完整性。 Query 是 Hibernate 提供的一个查询 API,我们可以使用它来执行 HQL 或 SQL 查询。 三、Problem and Solution 在使用 Hibernate 时,我们经常会遇到一些错误。本文将以 "org.hibernate.ObjectDeletedException: deleted instance passed to merge" 为例,介绍其原因及解决方案。 当我们试图将已删除的对象重新合并到 Session 中时,Hibernate 就会抛出这个异常。 这是因为在 Hibernate 中,对象的状态是被 Session 管理的。当你决定删掉一个对象时,Hibernate 这个小机灵鬼就会给这个对象打上“待删除”的标签,并且麻溜地把它从 Session 的列表里踢出去。 如果我们试图将一个已被删除的对象再次提交到 Session 中,Hibernate 就会抛出 ObjectDeletedException 异常。 解决这个问题的方法是在操作对象之前先检查其状态。如果对象已经被删除,我们就不能再次提交它。 四、Example Code 以下是一个简单的示例,展示了如何在 Hibernate 中使用 Session。 java import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class HibernateExample { public static void main(String[] args) { Configuration config = new Configuration(); config.configure("hibernate.cfg.xml"); Session session = config.getCurrent_session(); Transaction tx = null; try { tx = session.beginTransaction(); User user = new User("John Doe", "john.doe@example.com"); session.save(user); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } e.printStackTrace(); } finally { session.close(); } } } 在这个示例中,我们首先配置了一个 Hibernate 配置文件(hibernate.cfg.xml),然后打开了一个新的 Session。接着,我们开始了一个新的事务,然后保存了一个 User 对象。最后,我们提交了事务并关闭了 Session。 五、Conclusion Hibernate 是一个强大的 ORM 框架,它可以帮助我们更轻松地管理对象状态和关系。虽然在用 Hibernate 这个工具的时候,免不了会遇到一些让人头疼的小错误,不过别担心,只要我们把它的基本操作和内在原理摸清楚了,就能像变魔术一样轻松解决这些问题啦。通过持续地学习和动手实践,咱们能更溜地掌握 Hibernate 这门手艺,让我们的工作效率蹭蹭上涨,代码质量也更上一层楼。
2023-05-06 21:55:27
478
笑傲江湖-t
Hibernate
Hibernate中的TransactionRequiredException:执行更新/删除查询时的深入解析与应对策略 1. 引言 在我们日常开发中,Hibernate作为Java世界中最受欢迎的对象关系映射(ORM)框架之一,极大地简化了数据库操作。然而,在使用过程中,我们可能会遇到一些棘手的问题,比如“TransactionRequiredException: Executing an update/delete query”异常。这篇文章将带领大家深入剖析这个问题的根源,并通过实例代码进行演示和探讨解决方案。 2. 问题初识 在使用Hibernate执行更新或删除操作时,如果你没有正确地在一个事务上下文中执行这些操作,Hibernate将会抛出一个org.hibernate.TransactionRequiredException异常。这个状况常常意味着,你正打算进行的SQL更新或删除操作,就像是在跟数据库玩一场“原子游戏”,需要在一个完整的“交易回合”里完成。而现在呢,就像你两手空空,发现并没有一个有效的“交易回合”正在进行,所以游戏暂时没法玩下去啦。 例如,假设我们有一个简单的User实体类,并尝试在没有开启事务的情况下直接删除: java Session session = sessionFactory.openSession(); session.createQuery("delete from User where id = :id").setParameter("id", userId).executeUpdate(); 运行上述代码,你会遭遇TransactionRequiredException,这是因为Hibernate要求对数据库状态修改的操作必须在一个事务中进行,以确保数据的一致性和完整性。 3. 事务的重要性 为什么Hibernate要求在事务中执行更新/删除操作? 在数据库领域,事务是一个非常重要的概念,它保证了数据库操作的ACID特性(原子性、一致性、隔离性和持久性)。当你在进行更新或者删除这类操作的时候,如果没有事务安全机制保驾护航,一旦碰上个啥意外状况,比如程序突然罢工、网络说断就断,很可能出现的情况就是:有的操作成功了,有的却失败了。这样一来,数据的一致性可就被破坏得乱七八糟啦。 因此,Hibernate强制要求我们必须在一个开启的事务内执行这类可能改变数据库状态的操作,确保即使在出现问题时,也能通过事务的回滚机制恢复到一个一致的状态。 4. 解决方案及示例代码 如何正确地在Hibernate中开启并管理事务? 对于上述问题,我们需要在执行更新/删除操作前显式地开启一个事务,并在操作完成后根据业务需求提交或回滚事务。 下面是一个使用Hibernate Session API手动管理事务的例子: java Session session = sessionFactory.openSession(); Transaction transaction = null; try { // 开启事务 transaction = session.beginTransaction(); // 执行删除操作 session.createQuery("delete from User where id = :id").setParameter("id", userId).executeUpdate(); // 提交事务,确认更改 transaction.commit(); } catch (Exception e) { if (transaction != null && transaction.isActive()) { // 如果有异常发生,回滚事务 transaction.rollback(); } throw e; } finally { // 关闭Session session.close(); } 另外,对于更复杂的场景,我们可以借助Spring框架提供的事务管理功能,让事务管理变得更加简洁高效: java @Transactional public void deleteUser(Long userId) { Session session = sessionFactory.getCurrentSession(); session.createQuery("delete from User where id = :id").setParameter("id", userId).executeUpdate(); } 在此例子中,通过Spring的@Transactional注解,我们可以在方法级别自动管理事务,无需手动控制事务的开启、提交和回滚。 5. 结论 理解并正确处理Hibernate中的TransactionRequiredException异常是每个Hibernate开发者必备技能之一。通过妥善处理各项事务,咱们不仅能有效防止这类异常情况的发生,更能稳稳地保证系统数据的完整无缺和一致性,这样一来,整个应用程序就会健壮得像头牛,坚如磐石。希望本文能帮助你在面对类似问题时,能够迅速定位原因并采取恰当措施解决。记住,无论何时,当你打算修改数据库状态时,请始终不忘那个守护数据安全的“金钟罩”——事务。
2023-05-10 14:05:31
574
星辰大海
Hibernate
...开发人员以面向对象的方式来操作数据库。在Hibernate框架中,ORM使得Java开发者能够通过操作Java对象来间接实现对数据库表的CRUD(创建、读取、更新和删除)操作,而无需直接编写SQL语句。 Hibernate配置 , Hibernate配置是指在使用Hibernate框架时,需要定义的一系列关于数据源、实体类映射、事务管理等方面的设置信息。这些配置可以通过XML文件或注解方式进行,并用于初始化SessionFactory对象,它是Hibernate的核心配置容器,包含了所有持久化层操作所需的信息。 实体类 , 在面向对象编程和ORM框架(如Hibernate)中,实体类是对现实世界中某一具体事物的抽象,通常对应数据库中的一张表。实体类中包含了一系列属性(对应于表的字段)以及相关的方法,如getter/setter方法。当我们在Java程序中操作实体类对象时,Hibernate会自动将这些操作转换为对数据库中相应记录的操作。例如,在文章中提到的“User”实体类,可能就对应着数据库中的“users”表,其中的“username”属性则对应着表中的“username”字段。
2023-06-23 12:49:40
551
笑傲江湖-t
Hibernate
Hibernate与数据库表访问权限问题深度解析 1. 引言 在企业级应用开发中,Hibernate作为一款强大的ORM框架,极大地简化了Java对象与关系型数据库之间的映射操作。然而,在实际做项目的时候,我们常常会碰到关于数据库表权限分配的难题,尤其在那种用户多、角色乱七八糟的复杂系统里头,这个问题更是频繁出现。这篇文儿,咱们要接地气地聊聊Hibernate究竟是怎么巧妙应对和化解这类权限问题的,并且会结合实际的代码例子,掰开了揉碎了给你细细道来。 2. Hibernate与数据库权限概述 在使用Hibernate进行持久化操作时,开发者需要理解其底层是如何与数据库交互的。默认情况下,Hibernate是通过连接数据库的用户身份执行所有CRUD(创建、读取、更新、删除)操作的。这就意味着,这个用户的数据库权限将直接影响到应用能否成功完成业务逻辑。 3. 权限控制的重要性 假设我们的系统中有不同角色的用户,如管理员、普通用户等,他们对同一张数据表的访问权限可能大相径庭。例如,管理员可以完全操作用户表,而普通用户只能查看自己的信息。这个时候,咱们就得在Hibernate这个环节上动点小心思,搞个更精细化的权限管理,确保不会因为权限不够而整出什么操作失误啊,数据泄露之类的问题。 4. Hibernate中的权限控制实现策略 (a) 配置文件控制 首先,最基础的方式是通过配置数据库连接参数,让不同的用户角色使用不同的数据库账号登录,每个账号具有相应的权限限制。在Hibernate的hibernate.cfg.xml配置文件中,我们可以设置如下: xml admin secret (b) 动态SQL与拦截器 对于更复杂的场景,可以通过自定义拦截器或者HQL动态SQL来实现权限过滤。例如,当我们查询用户信息时,可以添加一个拦截器判断当前登录用户是否有权查看其他用户的数据: java public class AuthorizationInterceptor extends EmptyInterceptor { @Override public String onPrepareStatement(String sql) { // 获取当前登录用户ID Long currentUserId = getCurrentUserId(); return super.onPrepareStatement(sql + " WHERE user_id = " + currentUserId); } } (c) 数据库视图与存储过程 另外,还可以结合数据库自身的安全性机制,如创建只读视图或封装权限控制逻辑于存储过程中。Hibernate照样能搞定映射视图或者调用存储过程来干活儿,这样一来,我们就能在数据库这一层面对权限实现滴水不漏的管控啦。 5. 实践中的思考与挑战 尽管Hibernate提供了多种方式实现权限控制,但在实际应用中仍需谨慎对待。比如,你要是太过于依赖那个拦截器,就像是把所有鸡蛋放在一个篮子里,代码的侵入性就会蹭蹭上涨,维护起来能让你头疼到怀疑人生。而如果选择直接在数据库层面动手脚做权限控制,虽然听起来挺高效,但特别是在那些视图或者存储过程复杂得让人眼花缭乱的情况下,性能可是会大打折扣的。 因此,在设计权限控制系统时,我们需要根据系统的具体需求,结合Hibernate的功能特性以及数据库的安全机制,综合考虑并灵活运用各种策略,以达到既能保证数据安全,又能优化性能的目标。 6. 结语 总之,数据库表访问权限管理是构建健壮企业应用的关键一环,Hibernate作为 ORM 框架虽然不能直接提供全面的权限控制功能,但通过合理利用其扩展性和与数据库的良好配合,我们可以实现灵活且高效的权限控制方案。在这个历程里,理解、探索和实践就像是我们不断升级打怪的“能量饮料”,让我们一起在这场技术的大冒险中并肩前进,勇往直前。
2023-09-21 08:17:56
418
夜色朦胧
MyBatis
...yBatis拦截器是基于Java的动态代理机制实现的一种插件化设计,它允许我们在执行SQL映射语句前或后添加额外的操作。例如,我们可以利用拦截器进行日志记录、权限校验、性能监控等任务。 java @Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})}) public class MyInterceptor implements Interceptor { // 拦截方法的具体实现... } 2. MyBatis批量插入数据的方式 对于批量插入数据,MyBatis提供了BatchExecutor来支持这一功能。我们可以通过SqlSession的beginTransaction()开启批处理模式,然后连续调用insert()方法,最后再调用commit()提交事务。 java try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH)) { for (int i = 0; i < dataList.size(); i++) { User user = dataList.get(i); session.insert("com.example.mapper.UserMapper.insert", user); } session.commit(); } 3. 批量插入时拦截器为何失效? 然而,在这种批量插入场景下,细心的开发者会发现预设的拦截器并未按预期执行。这主要是因为MyBatis在批量模式下为了优化性能,采用了延迟加载的策略,即在真正执行commit()方法时才会一次性将所有待插入的数据发送到数据库,而不是每次调用insert()方法时就立即执行SQL。 因此,当我们在拦截器中监听Executor.update()方法时,由于在批量模式下此方法并没有实际执行SQL,只是将SQL命令缓存起来,所以导致了拦截器看似“失效”。 4. 解决方案 调整拦截器触发时机 为了解决这个问题,我们需要调整拦截器的触发时机,使其能够在批量操作最终提交时执行。一个切实可行的招儿是,咱们在拦截器那里“埋伏”一下,盯紧那个Transaction.commit()方法。这样一来,每当大批量数据要提交的时候,咱们就能趁机把自定义的逻辑给顺手执行了,保证不耽误事儿。 java @Intercepts({@Signature(type = Transaction.class, method = "commit", args = {})}) public class BatchInterceptor implements Interceptor { // 在事务提交时执行自定义逻辑... } 总结来说,理解MyBatis拦截器的工作原理,以及其在批量插入场景下的行为表现,有助于我们更好地应对各种复杂情况,让拦截器在提升应用灵活性和扩展性的同时,也能在批量操作这类特定场景下发挥应有的作用。在实际编程实战中,咱们得瞅准需求的实际情况,灵活机智地调整和设计拦截器启动的时机点,这样才能让它发挥出最大的威力,达到最理想的使用效果。
2023-05-12 21:47:49
152
寂静森林_
Hibernate
一、引言 Hibernate是一个开放源代码的对象关系映射框架,它允许我们把数据库操作抽象成对象间的交互,使得我们可以更加方便地处理数据。在实际操作Hibernate的时候,咱们免不了会碰上各种意想不到的小插曲,就比如说,其中一种常见的状况就是“org.hibernate.MappingException: Unknown entity”这个问题,它就像个淘气的小怪兽,时不时跳出来和我们捉迷藏。这篇文章将会详细介绍这个问题以及解决办法。 二、问题描述 当我们在使用Hibernate进行操作时,如果出现了“org.hibernate.MappingException: Unknown entity”的错误提示,那么就表示我们的程序无法识别某个实体类。这通常是由于以下几种情况导致的: 1. 我们在配置文件中没有正确地添加我们需要映射的实体类。 2. 我们的实体类定义存在错误,例如缺少必要的注解或者字段定义不正确等。 3. Hibernate的缓存没有正确地工作,导致其无法找到我们所需要的实体类。 三、解决方案 针对以上的情况,我们可以通过以下几种方式来解决问题: 1. 添加实体类到配置文件 首先,我们需要确保我们的实体类已经被正确地添加到了Hibernate的配置文件中。如果咱现在用的是XML配置文件这种方式,那就得在那个"class"标签里头,明确指定咱们的实体类。例如: php-template 如果我们使用的是Java配置文件,那么我们需要在@EntityScan注解中指定我们的实体类所在的包。例如: less @EntityScan("com.example") public class MyConfig { // ... } 2. 检查实体类定义 其次,我们需要检查我们的实体类定义是否存在错误。比如,咱们得保证咱们的实体类已经妥妥地标记上了@Entity这个小标签,而且,所有的属性都分配了正确的数据类型和相对应的注解,一个都不能少。此外,我们还需要确保我们的实体类实现了Serializable接口。 例如: java @Entity public class MyEntity implements Serializable { private Long id; private String name; // getters and setters } 3. 调整Hibernate缓存设置 最后,我们需要确保Hibernate的缓存已经正确地工作。如果我们的缓存没整对,Hibernate可能就抓不到我们想要的那个实体类了。我们可以通过调整Hibernate的缓存设置来解决这个问题。例如,我们可以禁用Hibernate的二级缓存,或者调整Hibernate的查询缓存策略。 例如: java Configuration cfg = new Configuration(); cfg.setProperty("hibernate.cache.use_second_level_cache", "false"); SessionFactory sessionFactory = cfg.buildSessionFactory(); 四、结论 总的来说,“org.hibernate.MappingException: Unknown entity”是一种常见的Hibernate错误,主要是由于我们的实体类定义存在问题或者是Hibernate的缓存设置不当导致的。根据以上提到的解决方法,咱们应该能顺顺利利地搞定这个问题,这样一来,咱就能更溜地用Hibernate来操作数据啦。同时,咱们也得留意到,Hibernate出错其实就像咱编程过程中的一个预警小喇叭,它在告诉我们:嗨,伙计们,你们的设计或者代码可能有需要打磨的地方啦!这正是我们深入检查代码、优化系统设计的好时机,这样一来,咱们的编程质量和效率才能更上一层楼。
2023-10-12 18:35:41
463
红尘漫步-t
.net
...修改或删除代码,从而实现诸如AOP(面向切面编程)等高级特性。 AOP(面向切面编程) , 面向切面编程是一种编程范式,它将横切关注点(如日志记录、事务管理、性能监控等)从主业务逻辑中抽离出来,以非侵入的方式统一管理和维护。在本文的上下文中,Fody作为一个AOP工具,通过自定义属性等方式,在编译时自动织入这些横切关注点,避免了代码重复,提高了开发效率和代码可维护性。 NuGet包 , NuGet是Microsoft开发并维护的一个开源的软件包管理器,专为.NET开发者设计,提供了一种简单便捷的方式来搜索、安装、更新和卸载第三方库或框架。在文章中提到,开发者需要在项目中安装Fody NuGet包,这意味着可以通过NuGet平台快速引入Fody工具,并利用其功能来解决代码重复问题。
2023-09-26 08:21:49
469
诗和远方-t
Struts2
...置选项。例如,新增了基于注解的异常处理方式,开发者可以直接在Action类的方法上声明预期处理的异常类型,进而映射到特定的结果视图,极大地提升了代码的可读性和维护性。 此外,针对近年来Web安全问题频发的情况,专家建议在设计Interceptor时应充分考虑安全性因素,如对输入参数进行严格过滤、防止恶意攻击等。一些第三方安全框架也提供了与Struts2集成的Interceptor实现,通过这些安全组件,开发者可以更高效地构建出健壮且安全的Web应用。 总之,掌握Struts2 Interceptor异常处理机制是Java Web开发人员的基本素养,而关注框架的最新动态并结合实际应用场景灵活运用,则有助于我们在应对复杂系统异常情况时更为得心应手,从而确保系统的稳定运行和用户数据的安全。
2023-03-08 09:54:25
159
风中飘零
Hibernate
...语言中的对象模型。在Hibernate框架中,ORM允许开发者以操作对象的方式来操作数据库记录,通过定义实体类与数据库表之间的对应关系,简化了数据访问层的设计和实现,提高了开发效率。 CascadeType , 在Hibernate中,CascadeType是一个枚举类型,用于指定实体关联关系之间操作的级联行为。例如,当我们在一对多或多对一关联关系上设置cascade=CascadeType.ALL时,这意味着对父实体执行任何持久化操作(如保存、更新或删除),这些操作会自动传播到所有关联的子实体上。 mappedBy属性 , 在双向关联关系中,mappedBy是Hibernate注解的一个属性,用于指定哪个实体类上的字段负责维护关联关系。例如,在User和Role的双向关联中,如果在Role实体类上使用@ManyToOne(mappedBy = \ user\ ),则表示关联关系由User实体类中的某个字段(如user)来维护,即基于该字段进行外键引用和关联更新。这样可以避免数据冗余和一致性问题,确保在进行持久化操作时,关联关系能够被正确且高效地管理。
2023-02-11 23:54:20
465
醉卧沙场
HBase
...是HBase用来保证事务一致性的一种机制。通俗点讲,对于每一条存放在HBase里的数据记录,它都会贴心地保存多个版本,每个版本都有一个独一无二的“身份证”——版本标识符。当进行读操作时,HBase会根据时间戳选择最接近当前时间的版本进行返回。这种方式既避免了读写冲突,又确保了读操作的实时性。 2. 时间戳 在HBase中,所有操作都依赖于时间戳。每次你进行写操作时,我们都会给它贴上一个崭新的时间标签。就像给信封盖邮戳一样,保证它的新鲜度。而当你进行读操作时,好比你在查收邮件,可以自由指定一个时间范围,去查找那个时间段内的信息内容。这样子,我们就可以通过对比时间戳,轻松找出哪个版本是最新的,就像侦探破案一样精准,这样一来,数据的一致性就妥妥地得到了保障。 3. 避免重复写入 为了防止因网络延迟等原因导致的数据不一致,HBase采用了锁定机制。每当你在HBase里写入一条新的记录,它就像个尽职的保安员,会立刻给这条记录上一把锁,死死守着不让别人动,直到你决定提交或者撤销这次操作。这种方式可以有效地避免重复写入,确保数据的一致性。 四、HBase的数据一致性示例 下面,我们通过一段简单的代码来展示HBase是如何保证数据一致性的。 java // 创建一个HBase客户端 HTable table = new HTable(conf, "test"); // 插入一条记录 Put put = new Put("row".getBytes()); put.add(Bytes.toBytes("column"), Bytes.toBytes("value")); table.put(put); // 读取这条记录 Get get = new Get("row".getBytes()); Result result = table.get(get); System.out.println(result.getValue(Bytes.toBytes("column"), Bytes.toBytes("value"))); 在这段代码中,我们首先创建了一个HBase客户端,并插入了一条记录。然后,我们读取了这条记录,并打印出它的值。由于HBase采用了MVCC和时间戳,所以每次读取到的都是最新的数据。 五、结论 总的来说,HBase通过采用MVCC、时间戳以及锁定等机制,成功地保证了数据的一致性。虽然这些机制可能会让咱们稍微多花点成本,不过在应对那种人山人海、数据海量的场面时,这点付出绝对是物有所值,完全可以接受的。因此,我们可以放心地使用HBase来处理大数据问题。
2023-09-03 18:47:09
467
素颜如水-t
Go-Spring
...-Spring是一个基于Go语言构建的轻量级企业级微服务框架,借鉴了Spring Boot的思想,提供了诸多特性以提高代码质量和可维护性。它通过依赖注入、AOP面向切面编程等技术手段,让开发者能够写出更清晰、更具扩展性的代码。 3. 依赖注入提升代码质量 - 示例1 go type UserService struct { userRepository UserRepository } func NewUserService(repo UserRepository) UserService { return &UserService{userRepository: repo} } func (s UserService) GetUser(id int) User { return s.userRepository.FindById(id) } 上述代码展示了Go-Spring中的依赖注入实践。拿捏一下,我们这样来理解:就像给UserService找个得力助手UserRepository,通过一种叫做构造函数注入的方式,让它们俩能够独立工作又互相配合。这样一来,不仅让我们的代码更容易进行测试,还使得整个系统架构变得更灵活,想扩展或者维护的时候,那叫一个轻松加愉快啊! 4. 面向切面编程增强可维护性 - 示例2 go type LoggingAspect struct{} func (l LoggingAspect) Before(target interface{}, method reflect.Method, args []reflect.Value) error { log.Printf("Executing method %s of type %T", method.Name, target) return nil } // 注册切面 spring.RegisterBean(new(LoggingAspect)).AsAop(".") // 假设我们有一个被切面拦截的方法 type MyService struct{} func (m MyService) Process() {} 在这个例子中,Go-Spring的AOP功能允许我们在不修改原有业务逻辑的前提下,对特定方法进行统一的日志处理。这种非侵入式的编程方式极大地增强了代码的可维护性和复用性。 5. 组件化管理与模块化设计 Go-Spring倡导组件化管理和模块化设计,通过其提供的自动配置、条件注解等功能,可以实现模块的独立开发、独立测试以及按需加载,从而降低模块间的耦合度,提高代码质量和可维护性。 6. 结语 在当今快节奏的开发环境中,选择正确的工具和技术框架至关重要。Go-Spring这个家伙,它有着自己独特的设计理念和牛哄哄的功能特性,实实在在地帮我们在提升Go应用程序的代码质量和维护便捷性上撑起了腰杆子。不过,要让这些特性真正火力全开,发挥作用,咱们得在实际开发的过程中,像啃透一本好书那样深入理解它们,并且练就得炉火纯青。同时,也要结合咱团队独家秘籍——最佳实践,不断打磨、优化我们的代码质量,让它既结实耐用又易于维护,就像保养爱车一样精心对待。毕竟,每个优秀的项目背后,都离不开一群热爱并执着于代码优化的人们,他们思考、探索,用智慧和热情塑造着每一行代码的质量和生命力。
2023-09-19 21:39:01
482
素颜如水
SpringCloud
...要配置一些Bean来实现特定的功能。而这些Bean通常是通过@Configuration注解来定义的。然而,在真实世界的应用场景里,我们往往会发现一个秘密:@Configuration类竟然会被偷偷地做代理处理。你可能会问,哎,这是为啥呢?这就得揭开@Configuration类被代理背后的神秘面纱啦! 二、@Configuration类被代理的原理 在了解@Configuration类被代理的原理之前,我们需要了解一下什么是代理。代理是一种设计模式,它可以作为其他对象的一个替身或者行为的包装器。当你想要给某个东西加点料,改改它的表现方式时,咱们可以脑洞大开,造个替身出来,让它代替原本的那个家伙去干活儿,这样一来,就轻而易举地实现了我们的小目标。 那么@Configuration类是如何被代理的呢?让我们一起来看看Spring的源码吧! 三、源码解析 在Spring的源码中,当我们使用@Configuration注解的时候,实际上Spring会对这个类进行一些特殊的处理。首先,Spring会创建一个代理对象来替代@Configuration类本身。然后,你瞧这啊,当程序去呼唤@Configuration这个类里面的方法时,实际上它玩的是代理对象的小把戏,就是在调用代理对象的方法呢。 在这个过程中,Spring做了两件事情: 1. 保存原始类的引用 在创建代理对象的时候,Spring会保存原始类的引用,以便在需要的时候能够恢复到原始类。这是因为代理对象就像是原始类的一个分身小弟,它代替原始类执行任务。但如果我们让它完全取代了原始类这位“大哥”,那我们可就摸不着头脑了,没法再去调用原始类那些特有的方法和属性了。 2. 添加拦截器 在创建代理对象的时候,Spring还会添加一些拦截器。这些拦截器会在代理对象执行方法之前和之后做一些额外的操作。比如说,我们可以插一个拦截器,就像一个小秘书那样,专门记录下每次方法被调用的具体时间。这样一来,我们就能像看手表一样,实时掌握系统的运行效率和性能状况了。 这就是@Configuration类被代理的基本原理。下面我们来看一个具体的例子。 四、实战演示 假设我们有一个@Service类,它里面有一些业务逻辑。现在呢,我们想要实时地盯着这些业务逻辑的运行状况,就像有个小雷达一样随时监测。所以,咱们琢磨了一下,决定动手用Spring的那个强大的AOP功能,来帮我们达成这个小心愿。不过,在配置的过程中,我们碰到了个不大不小的难题,那就是咱们还没搞清楚到底该在哪些环节巧妙地插入AOP的切面。这时,我们就需要用到@Configuration类了。 在@Configuration类中,我们可以添加一个@Bean注解来声明一个Bean。而在@Bean注解后面,我们可以添加一个方法来返回这个Bean。那么,如果我们想要给这个Bean添加一个切面,我们应该怎么做呢? 这时,我们就需要用到Spring的AOP功能了。我们可以用@Aspect这个小家伙来标记一个切面,接着再通过@Pointcut这个小帮手来确定我们要切入的具体位置。就像是在编程的世界里画了个“切割符号”,先声明“我要处理哪一类事情”(切面),再具体指定“在哪儿动手做”(切点)。最后,我来给你说个有趣的事情,我们可以用一个叫@Around的神奇小标签,给它定义一个“通知员”的角色。每当找到符合条件的方法要开始执行或者已经执行完毕时,这位“通知员”就会自动出场,前后忙活起来。 然后,我们将这个切面注入到Spring的ApplicationContext中,这样就可以在运行的时候使用这个切面了。 五、总结 @Configuration类被代理是Spring的一种重要特性,它为我们提供了一种方便的方式来管理和配置Bean。了解了@Configuration类被代理的原理后,咱们就能更深入地掌握Spring的AOP功能,而且能够随心所欲地运用@Configuration类来满足咱们的各种需求,让编程变得更加游刃有余。
2023-10-23 20:18:43
128
海阔天空_t
RabbitMQ
...MQ服务器发送消息来实现数据传输和消息处理等功能。在一些关键的业务场合,我们常常得保证消息能够像百米赛跑那样,稳稳当当地跑到接收方手中,一个字儿都不能错。而且,就算半路上出了什么岔子,也得有办法把那完整的消息给抢救回来,不丢一分一毫。这时,我们就需要利用RabbitMQ中的事务性消息发送功能。 二、什么是事务性消息发送? 在RabbitMQ中,事务性消息发送是一种特殊的处理方式,它可以在消息传递过程中提供原子性的操作保障,即所有的操作要么全部成功,要么全部失败,不存在中间状态。说白了,就是假设有这么个情况,我们在发消息的时候突然出了点岔子,这时候RabbitMQ可机灵着呢,它会自动把已经发出的所有消息都撤回来,这样一来,咱的消息就能保持原汁原味,完整性妥妥的得到保障啦。 三、如何在RabbitMQ中实现事务性消息发送? 要实现事务性消息发送,我们需要首先创建一个事务管理器,并将其绑定到RabbitMQ连接上。接下来,我们可以直接用这个事务管理器开启一个新的交易,然后在新开的这个交易里头,放心大胆地发送消息就对了。最后,我们需要调用事务管理器的commit方法来提交事务,或者调用其rollback方法来回滚事务。 下面是一个具体的示例: java import com.rabbitmq.client.; public class TransactionalProducer { private final Connection connection; private final Channel channel; public TransactionalProducer(String host, int port) throws IOException { // 创建连接和通道 this.connection = new Connection(host, port); this.channel = connection.createChannel(); } public void sendMessage(String exchangeName, String routingKey, String message) throws IOException { // 开始一个新的事务 channel.txSelect(); // 发送消息 channel.basicPublish(exchangeName, routingKey, null, message.getBytes()); // 提交事务 channel.txCommit(); } public static void main(String[] args) throws IOException { TransactionalProducer producer = new TransactionalProducer("localhost", 5672); producer.sendMessage("hello-exchange", "hello-routing-key", "Hello World!"); } } 在这个示例中,我们首先创建了一个新的交易连接,并从中获取到了一个交易频道。接着呢,我们就像这样操作的:在把消息发送出去之前,先启动了一个全新的事务,这一步就是通过调用txSelect方法来完成的。而等到消息成功发送出去之后,咱们再潇洒地执行txCommit方法,这就意味着那个事务被顺利提交啦。这样,即使在发送消息的过程中出现了异常,RabbitMQ也会自动撤销已经发送的所有消息,从而保证了消息的完整性和一致性。 四、结论 总的来说,在RabbitMQ中实现事务性消息发送是一项非常重要的功能,它可以为我们提供原子性的操作保障,避免因为单个操作失败而导致的数据丢失或损坏。而通过上面的示例,我们也看到其实现起来并不复杂,只需要简单地几步操作即可。所以,如果你正在用RabbitMQ搞数据传输、处理消息这些活儿,那你就得把这个功能玩得溜溜的,确保在关键时刻能把它物尽其用,一点儿不浪费。
2023-02-21 09:23:08
99
青春印记-t
c#
...ase First的方式提供了一种强类型化的方式来操作数据库,大大减少了手动编写SQL命令的需求,并内置了丰富的数据验证与异常处理机制。 近期,.NET 5(现演进为.NET 6)对EF Core进行了全面优化,支持更多数据库引擎,增强了LINQ查询能力,还引入了延时加载、批处理插入等功能,有效提升了数据插入及其他数据库操作的性能。此外,对于并发控制和事务管理,.NET 6也提供了更为精细的控制手段,确保数据的一致性和完整性。 因此,在面对数据库操作问题时,除了手工封装SqlHelper类进行原始SQL命令执行外,开发者还可以关注并研究如何充分利用现代ORM框架的优势来解决类似的数据插入问题,以适应不断变化的技术环境和项目需求,进一步提升代码质量和开发效率。同时,结合领域驱动设计(DDD)等架构设计理念,可以更好地组织业务逻辑和数据访问层,实现更高级别的抽象和解耦,从而应对未来可能出现的各种新挑战。
2023-08-19 17:31:31
469
醉卧沙场_
MyBatis
...库连接信息、映射器、事务管理等重要设置。如果这些属性值不小心没了,或者配错了,那可就麻烦大了,很可能会让咱连数据库的大门都进不去,查询结果也可能会变得奇奇怪怪的。这样一来,就会引发一连串的问题,严重到足以让整个应用运行起来磕磕绊绊,甚至罢工。 3. 常见的配置属性丢失或错误场景 场景一:数据库连接属性丢失 xml 在此场景下,由于缺少必要的数据库连接属性,MyBatis无法正常初始化数据源,进而导致后续的数据操作失败。 场景二:映射器配置路径错误 xml 映射器配置路径如果出现错误,会导致MyBatis找不到对应的映射文件,从而无法执行相关的SQL语句。 4. 探讨与分析 当面对配置文件中的属性丢失或错误时,首先需要有敏锐的洞察力和细致的排查态度。比方说,当数据库连接突然罢工了,咱就得去瞅瞅日志输出,像侦探破案那样揪出错误的源头;再假如映射文件加载不给力出了岔子,咱可以通过IDE这个小助手的项目结构导航功能,或者亲自去磁盘里翻翻路径,来验证一下配置是否被咱们正确地安排上了。 5. 解决方案与预防措施 - 解决方案: - 对于属性丢失的问题,根据错误提示找到对应位置,补充正确的属性值。 - 对于配置错误的情况,核实并修正错误的路径或属性值。 - 预防措施: - 使用IDE的代码提示和格式化功能,确保配置文件的完整性。 - 在编写和修改配置文件后,及时进行单元测试,尽早发现问题。 - 采用环境变量或配置中心统一管理敏感信息,避免硬编码在配置文件中。 6. 结论 理解和掌握MyBatis配置文件的正确使用方式是至关重要的,任何一个微小的疏忽都可能导致严重的运行时问题。当咱们遇到“配置文件里的属性神秘失踪或出错”这种情况时,可千万别慌不择路、急于求成,要稳住心态,像福尔摩斯破案那样冷静分析问题。然后,咱们得运用那些实打实有效的调试方法,第一时间把错误给纠正过来。而且,每一次解决这种小插曲的过程,都是咱们积累宝贵经验的好机会,这样一来,咱的开发技能和解决问题的能力也能噌噌噌地往上提升呢!同时,养成良好的编码习惯,持续优化配置管理,可以有效降低此类问题的发生概率。
2023-02-07 13:55:44
191
断桥残雪_
MyBatis
...以及如何通过结合注解方式进行SQL映射以提升代码可读性。 同时,数据库性能优化领域,一篇名为“利用MyBatis进行SQL性能调优”的技术博客强调了SQL执行计划分析的重要性,并指导读者如何借助MyBatis的日志输出功能,结合数据库自身的性能分析工具(如MySQL的EXPLAIN),对查询语句进行深度优化,从而确保系统在大数据量下仍能保持高效率运行。 此外,针对数据完整性保护,业界专家在《Java持久层设计模式》一书中提出了一系列策略,包括合理使用MyBatis的事务管理机制,以及通过预编译SQL、参数化查询等方式防止SQL注入攻击,这些内容都为提高MyBatis应用的安全性提供了有力指导。 综上所述,无论是紧跟技术前沿,了解MyBatis框架的最新发展,还是深入探究SQL性能优化与安全防护的实战经验,都是每一位使用MyBatis进行持久层开发的程序员不可忽视的重要延伸阅读内容。通过不断学习与实践,我们能够更好地驾驭MyBatis,实现系统的稳定、高效和安全运行。
2024-02-04 11:31:26
52
岁月如歌
ActiveMQ
...,并具备消息持久化、事务处理、负载均衡等高级特性。 JMS (Java Message Service) , Java消息服务是Java平台上用于消息中间件的一套API标准,定义了一组接口和类,使得开发人员能够编写与具体消息中间件产品无关的应用程序代码。JMS允许应用程序创建、发送、接收、读取以及管理消息,从而实现基于消息的异步通信和解耦。在文章中,通过使用JMS API,开发者可以创建连接、会话、目的地(如队列或主题)、消息生产者和消费者,以与ActiveMQ服务器进行交互。
2023-11-19 13:07:41
455
秋水共长天一色-t
Etcd
...他们通过引入Etcd实现了跨数据中心的库存同步管理,显著提升了系统的可用性和响应速度。这一成功实践不仅证明了Etcd在高并发场景下的稳定性,也展示了其在大规模分布式系统中的广泛应用前景。 与此同时,Etcd社区也在不断迭代更新,最新版本已支持更多高级特性,例如更高效的压缩算法和更强的安全加密机制。这些改进使得Etcd在面对日益复杂的分布式环境时更具竞争力。值得一提的是,国内某大型云计算服务商近日宣布将全面支持Etcd 3.x系列,并计划在未来几个月内推出基于Etcd的托管服务,为企业用户提供更加便捷的部署和管理体验。 此外,关于分布式事务管理的话题,近期有专家指出,尽管Etcd提供了强大的工具集,但在实际应用中仍需谨慎对待事务的粒度和范围。过细的事务划分可能导致性能瓶颈,而过于粗略的设计则可能引发数据不一致的风险。因此,在设计分布式事务时,需要综合考虑业务逻辑、系统规模以及硬件资源等因素,制定合理的策略。 最后,回顾历史,我们可以发现,无论是早期的ZooKeeper还是如今的Etcd,这类分布式协调服务始终伴随着分布式计算的发展而演进。正如《分布式系统设计》一书中提到的:“分布式系统的设计是一门艺术,它要求我们在灵活性与可靠性之间找到平衡。”未来,随着5G、物联网等新技术的兴起,分布式系统的复杂性将进一步增加,而像Etcd这样的工具无疑将在其中扮演越来越重要的角色。
2025-03-21 15:52:27
54
凌波微步
转载文章
...(); } 第五步:实现DAO接口 在dao包下创建一个UserMapper.xml文件作为上一步创建的DAO接口的实现。 [html] view plaincopy print? <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace:必须与对应的接口全类名一致 id:必须与对应接口的某个对应的方法名一致 --> <mapper namespace="com.tgb.mapper.UserMapper"> <insert id="save" parameterType="User"> insert into t_user(user_name,user_age) values({userName},{age}) </insert> <update id="update" parameterType="User"> update t_user set user_name={userName},user_age={age} where user_id={id} </update> <delete id="delete" parameterType="int"> delete from t_user where user_id={id} </delete> <!-- mybsits_config中配置的alias类别名,也可直接配置resultType为类路劲 --> <select id="findById" parameterType="int" resultType="User"> select user_id id,user_name userName,user_age age from t_user where user_id={id} </select> <select id="findAll" resultType="User"> select user_id id,user_name userName,user_age age from t_user </select> </mapper> 这里对这个xml文件作几点说明: 1、namespace必须与对应的接口全类名一致。 2、id必须与对应接口的某个对应的方法名一致即必须要和UserMapper.java接口中的方法同名。 第六步:Mybatis和Spring的整合 对于Mybatis和Spring的整合是这篇博文的重点,需要配置的内容在下面有详细的解释。 [html] view plaincopy print? <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 1. 数据源 : DriverManagerDataSource --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="123456" /> </bean> <!-- 2. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源 MyBatis定义数据源,同意加载配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:config/mybatis-config.xml" /> </bean> <!-- 3. mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory basePackage:指定sql映射文件/接口所在的包(自动扫描) --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.tgb.mapper"></property> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> <!-- 4. 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 5. 使用声明式事务 transaction-manager:引用上面定义的事务管理器 --> <tx:annotation-driven transaction-manager="txManager" /> </beans> 第七步:mybatis的配置文件 [html] view plaincopy print? <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 实体类,简称 -设置别名 --> <typeAliases> <typeAlias alias="User" type="com.tgb.model.User" /> </typeAliases> <!-- 实体接口映射资源 --> <!-- 说明:如果xxMapper.xml配置文件放在和xxMapper.java统一目录下,mappers也可以省略,因为org.mybatis.spring.mapper.MapperFactoryBean默认会去查找与xxMapper.java相同目录和名称的xxMapper.xml --> <mappers> <mapper resource="com/tgb/mapper/userMapper.xml" /> </mappers> </configuration> 总结 Mybatis和Spring的集成相对而言还是很简单的,祝你成功。 源码下载:SpringMVC+Spring4+Mybatis3 下篇博文我们将Hibernate和Mybatis进行一下详细的对比。 本篇文章为转载内容。原文链接:https://blog.csdn.net/konglongaa/article/details/51706991。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-09-05 11:56:25
111
转载
转载文章
分布式事务 , 在分布式系统中,涉及多个数据库或服务的事务处理,需要保证这些操作要么全部成功执行,要么全部回滚,以维护数据的一致性。文章中的场景是支付宝转账余额宝,当用户发起转账请求时,扣款和增款两个操作分别发生在不同的数据库(支付宝数据库和余额宝数据库)中,这就需要用到分布式事务来确保转账操作的原子性和一致性。 XA协议 , XA (eXtended Architecture) 是一种由 X/Open 组织定义的分布式事务处理标准,它为分布式事务管理器提供了一种跨多个资源(如数据库)进行协调的方式。在支付宝转账余额宝的例子中,XA协议允许一个事务管理器统一控制支付宝和余额宝两个数据库的事务,实现两阶段提交,从而确保两个数据库的数据一致性。 消息中间件 , 消息中间件是一种软件组件,用于应用程序之间传递异步消息,实现解耦、可靠传输和消息队列等功能。在文中提到的基于ActiveMQ的解决方案中,消息中间件充当了分布式事务协调者角色。当支付宝完成扣款后,会将消息插入到message表并发送至ActiveMQ,余额宝从消息队列消费消息并执行增款操作,通过这种方式实现了不同系统间的通信和事务协调,同时利用message表防止消息丢失和重复消费问题,确保了分布式事务的最终一致性。
2023-04-16 22:34:52
499
转载
转载文章
...y-Value存储 事务处理与数据分析处理混合型数据库 支持丰富的SQL语句类型,比如:关联子查询 支持绝大部分PostgreSQL的SQL语句 分布式多版本并发控制(MVCC:Multi-version Concurrency Control) 支持JSON和XML格式 Postgres-XL缺少的功能 内建的高可用机制 使用外部机制实现高可能,如:Corosync/Pacemaker 有未来功能提升的空间 增加节点/重新分片数据(re-shard)的简便性 数据重分布(redistribution)期间会锁表 可采用预分片(pre-shard)方式解决,在同台物理服务器上建立多个数据节点,每个节点存储一个数据分片。数据重分布时,将一些数据节点迁出即可 某些外键、唯一性约束功能 Postgres-XL架构 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-M9lFuEIP-1640133702200)(./assets/postgre-xl.jpg)] 基于开源项目Postgres-XC XL增加了MPP,允许数据节点间直接通讯,交换复杂跨节点关联查询相关数据信息,减少协调器负载。 多个协调器(Coordinator) 应用程序的数据库连入点 分析查询语句,生成执行计划 多个数据节点(DataNode) 实际的数据存储 数据自动打散分布到集群中各数据节点 本地执行查询 一个查询在所有相关节点上并行查询 全局事务管理器(GTM:Global Transaction Manager) 提供事务间一致性视图 部署GTM Proxy实例,以提高性能 Postgre-XL主要组件 GTM (Global Transaction Manager) - 全局事务管理器 GTM是Postgres-XL的一个关键组件,用于提供一致的事务管理和元组可见性控制。 GTM Standby GTM的备节点,在pgxc,pgxl中,GTM控制所有的全局事务分配,如果出现问题,就会导致整个集群不可用,为了增加可用性,增加该备用节点。当GTM出现问题时,GTM Standby可以升级为GTM,保证集群正常工作。 GTM-Proxy GTM需要与所有的Coordinators通信,为了降低压力,可以在每个Coordinator机器上部署一个GTM-Proxy。 Coordinator --协调器 协调器是应用程序到数据库的接口。它的作用类似于传统的PostgreSQL后台进程,但是协调器不存储任何实际数据。实际数据由数据节点存储。协调器接收SQL语句,根据需要获取全局事务Id和全局快照,确定涉及哪些数据节点,并要求它们执行(部分)语句。当向数据节点发出语句时,它与GXID和全局快照相关联,以便多版本并发控制(MVCC)属性扩展到集群范围。 Datanode --数据节点 用于实际存储数据。表可以分布在各个数据节点之间,也可以复制到所有数据节点。数据节点没有整个数据库的全局视图,它只负责本地存储的数据。接下来,协调器将检查传入语句,并制定子计划。然后,根据需要将这些数据连同GXID和全局快照一起传输到涉及的每个数据节点。数据节点可以在不同的会话中接收来自各个协调器的请求。但是,由于每个事务都是惟一标识的,并且与一致的(全局)快照相关联,所以每个数据节点都可以在其事务和快照上下文中正确执行。 Postgres-XL继承了PostgreSQL Postgres-XL是PostgreSQL的扩展并继承了其很多特性: 复杂查询 外键 触发器 视图 事务 MVCC(多版本控制) 此外,类似于PostgreSQL,用户可以通过多种方式扩展Postgres-XL,例如添加新的 数据类型 函数 操作 聚合函数 索引类型 过程语言 安装 环境说明 由于资源有限,gtm一台、另外两台身兼数职。 主机名 IP 角色 端口 nodename 数据目录 gtm 192.168.20.132 GTM 6666 gtm /nodes/gtm 协调器 5432 coord1 /nodes/coordinator xl1 192.168.20.133 数据节点 5433 node1 /nodes/pgdata gtm代理 6666 gtmpoxy01 /nodes/gtm_pxy1 协调器 5432 coord2 /nodes/coordinator xl2 192.168.20.134 数据节点 5433 node2 /nodes/pgdata gtm代理 6666 gtmpoxy02 /nodes/gtm_pxy2 要求 GNU make版本 3.8及以上版本 [root@pg ~] make --versionGNU Make 3.82Built for x86_64-redhat-linux-gnuCopyright (C) 2010 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law. 需安装GCC包 需安装tar包 用于解压缩文件 默认需要GNU Readline library 其作用是可以让psql命令行记住执行过的命令,并且可以通过键盘上下键切换命令。但是可以通过--without-readline禁用这个特性,或者可以指定--withlibedit-preferred选项来使用libedit 默认使用zlib压缩库 可通过--without-zlib选项来禁用 配置hosts 所有主机上都配置 [root@xl2 11] cat /etc/hosts127.0.0.1 localhost192.168.20.132 gtm192.168.20.133 xl1192.168.20.134 xl2 关闭防火墙、Selinux 所有主机都执行 关闭防火墙: [root@gtm ~] systemctl stop firewalld.service[root@gtm ~] systemctl disable firewalld.service selinux设置: [root@gtm ~]vim /etc/selinux/config 设置SELINUX=disabled,保存退出。 This file controls the state of SELinux on the system. SELINUX= can take one of these three values: enforcing - SELinux security policy is enforced. permissive - SELinux prints warnings instead of enforcing. disabled - No SELinux policy is loaded.SELINUX=disabled SELINUXTYPE= can take one of three two values: targeted - Targeted processes are protected, minimum - Modification of targeted policy. Only selected processes are protected. mls - Multi Level Security protection. 安装依赖包 所有主机上都执行 yum install -y flex bison readline-devel zlib-devel openjade docbook-style-dsssl gcc 创建用户 所有主机上都执行 [root@gtm ~] useradd postgres[root@gtm ~] passwd postgres[root@gtm ~] su - postgres[root@gtm ~] mkdir ~/.ssh[root@gtm ~] chmod 700 ~/.ssh 配置SSH免密登录 仅仅在gtm节点配置如下操作: [root@gtm ~] su - postgres[postgres@gtm ~] ssh-keygen -t rsa[postgres@gtm ~] cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys[postgres@gtm ~] chmod 600 ~/.ssh/authorized_keys 将刚生成的认证文件拷贝到xl1到xl2中,使得gtm节点可以免密码登录xl1~xl2的任意一个节点: [postgres@gtm ~] scp ~/.ssh/authorized_keys postgres@xl1:~/.ssh/[postgres@gtm ~] scp ~/.ssh/authorized_keys postgres@xl2:~/.ssh/ 对所有提示都不要输入,直接enter下一步。直到最后,因为第一次要求输入目标机器的用户密码,输入即可。 下载源码 下载地址:https://www.postgres-xl.org/download/ [root@slave ~] ll postgres-xl-10r1.1.tar.gz-rw-r--r-- 1 root root 28121666 May 30 05:21 postgres-xl-10r1.1.tar.gz 编译、安装Postgres-XL 所有节点都安装,编译需要一点时间,最好同时进行编译。 [root@slave ~] tar xvf postgres-xl-10r1.1.tar.gz[root@slave ~] ./configure --prefix=/home/postgres/pgxl/[root@slave ~] make[root@slave ~] make install[root@slave ~] cd contrib/ --安装必要的工具,在gtm节点上安装即可[root@slave ~] make[root@slave ~] make install 配置环境变量 所有节点都要配置 进入postgres用户,修改其环境变量,开始编辑 [root@gtm ~]su - postgres[postgres@gtm ~]vi .bashrc --不是.bash_profile 在打开的文件末尾,新增如下变量配置: export PGHOME=/home/postgres/pgxlexport LD_LIBRARY_PATH=$PGHOME/lib:$LD_LIBRARY_PATHexport PATH=$PGHOME/bin:$PATH 按住esc,然后输入:wq!保存退出。输入以下命令对更改重启生效。 [postgres@gtm ~] source .bashrc --不是.bash_profile 输入以下语句,如果输出变量结果,代表生效 [postgres@gtm ~] echo $PGHOME 应该输出/home/postgres/pgxl代表生效 配置集群 生成pgxc_ctl.conf配置文件 [postgres@gtm ~] pgxc_ctl prepare/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash.ERROR: File "/home/postgres/pgxl/pgxc_ctl/pgxc_ctl.conf" not found or not a regular file. No such file or directoryInstalling pgxc_ctl_bash script as /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxl/pgxc_ctl --configuration /home/postgres/pgxl/pgxc_ctl/pgxc_ctl.confFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxl/pgxc_ctl 配置pgxc_ctl.conf 新建/home/postgres/pgxc_ctl/pgxc_ctl.conf文件,编辑如下: 对着模板文件一个一个修改,否则会造成初始化过程出现各种神奇问题。 pgxcInstallDir=$PGHOMEpgxlDATA=$PGHOME/data pgxcOwner=postgres---- GTM Master -----------------------------------------gtmName=gtmgtmMasterServer=gtmgtmMasterPort=6666gtmMasterDir=$pgxlDATA/nodes/gtmgtmSlave=y Specify y if you configure GTM Slave. Otherwise, GTM slave will not be configured and all the following variables will be reset.gtmSlaveName=gtmSlavegtmSlaveServer=gtm value none means GTM slave is not available. Give none if you don't configure GTM Slave.gtmSlavePort=20001 Not used if you don't configure GTM slave.gtmSlaveDir=$pgxlDATA/nodes/gtmSlave Not used if you don't configure GTM slave.---- GTM-Proxy Master -------gtmProxyDir=$pgxlDATA/nodes/gtm_proxygtmProxy=y gtmProxyNames=(gtm_pxy1 gtm_pxy2) gtmProxyServers=(xl1 xl2) gtmProxyPorts=(6666 6666) gtmProxyDirs=($gtmProxyDir $gtmProxyDir) ---- Coordinators ---------coordMasterDir=$pgxlDATA/nodes/coordcoordNames=(coord1 coord2) coordPorts=(5432 5432) poolerPorts=(6667 6667) coordPgHbaEntries=(0.0.0.0/0)coordMasterServers=(xl1 xl2) coordMasterDirs=($coordMasterDir $coordMasterDir)coordMaxWALsernder=0 没设置备份节点,设置为0coordMaxWALSenders=($coordMaxWALsernder $coordMaxWALsernder) 数量保持和coordMasterServers一致coordSlave=n---- Datanodes ----------datanodeMasterDir=$pgxlDATA/nodes/dn_masterprimaryDatanode=xl1 主数据节点datanodeNames=(node1 node2)datanodePorts=(5433 5433) datanodePoolerPorts=(6668 6668) datanodePgHbaEntries=(0.0.0.0/0)datanodeMasterServers=(xl1 xl2)datanodeMasterDirs=($datanodeMasterDir $datanodeMasterDir)datanodeMaxWalSender=4datanodeMaxWALSenders=($datanodeMaxWalSender $datanodeMaxWalSender) 集群初始化,启动,停止 初始化 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all 输出结果: /bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlStopping all the coordinator masters.Stopping coordinator master coord1.Stopping coordinator master coord2.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existpg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord2" does not existDone.Stopping all the datanode masters.Stopping datanode master datanode1.Stopping datanode master datanode2.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.Stop GTM masterwaiting for server to shut down.... doneserver stopped[postgres@gtm ~]$ echo $PGHOME/home/postgres/pgxl[postgres@gtm ~]$ ll /home/postgres/pgxl/pgxc/nodes/gtm/gtm.^C[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlInitialize GTM masterERROR: target directory (/home/postgres/pgxc/nodes/gtm) exists and not empty. Skip GTM initilializationDone.Start GTM masterserver startingInitialize all the coordinator masters.Initialize coordinator master coord1.ERROR: target coordinator master coord1 is running now. Skip initilialization.Initialize coordinator master coord2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting coordinator master.Starting coordinator master coord1ERROR: target coordinator master coord1 is already running now. Skip initialization.Starting coordinator master coord22019-05-30 21:09:25.562 EDT [2148] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:09:25.562 EDT [2148] LOG: listening on IPv6 address "::", port 54322019-05-30 21:09:25.563 EDT [2148] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:09:25.601 EDT [2149] LOG: database system was shut down at 2019-05-30 21:09:22 EDT2019-05-30 21:09:25.605 EDT [2148] LOG: database system is ready to accept connections2019-05-30 21:09:25.612 EDT [2156] LOG: cluster monitor startedDone.Initialize all the datanode masters.Initialize the datanode master datanode1.Initialize the datanode master datanode2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting all the datanode masters.Starting datanode master datanode1.WARNING: datanode master datanode1 is running now. Skipping.Starting datanode master datanode2.2019-05-30 21:09:33.352 EDT [2404] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:09:33.352 EDT [2404] LOG: listening on IPv6 address "::", port 154322019-05-30 21:09:33.355 EDT [2404] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:09:33.392 EDT [2404] LOG: redirecting log output to logging collector process2019-05-30 21:09:33.392 EDT [2404] HINT: Future log output will appear in directory "pg_log".Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf stop all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlStopping all the coordinator masters.Stopping coordinator master coord1.Stopping coordinator master coord2.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existDone.Stopping all the datanode masters.Stopping datanode master datanode1.Stopping datanode master datanode2.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.Stop GTM masterwaiting for server to shut down.... doneserver stopped[postgres@gtm ~]$ pgxc_ctl/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlPGXC monitor allNot running: gtm masterRunning: coordinator master coord1Not running: coordinator master coord2Running: datanode master datanode1Not running: datanode master datanode2PGXC stop coordinator master coord1Stopping coordinator master coord1.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existDone.PGXC stop datanode master datanode1Stopping datanode master datanode1.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.PGXC monitor allNot running: gtm masterRunning: coordinator master coord1Not running: coordinator master coord2Running: datanode master datanode1Not running: datanode master datanode2PGXC monitor allNot running: gtm masterNot running: coordinator master coord1Not running: coordinator master coord2Not running: datanode master datanode1Not running: datanode master datanode2PGXC exit[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlInitialize GTM masterERROR: target directory (/home/postgres/pgxc/nodes/gtm) exists and not empty. Skip GTM initilializationDone.Start GTM masterserver startingInitialize all the coordinator masters.Initialize coordinator master coord1.Initialize coordinator master coord2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting coordinator master.Starting coordinator master coord1Starting coordinator master coord22019-05-30 21:13:03.998 EDT [25137] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:13:03.998 EDT [25137] LOG: listening on IPv6 address "::", port 54322019-05-30 21:13:04.000 EDT [25137] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:13:04.038 EDT [25138] LOG: database system was shut down at 2019-05-30 21:13:00 EDT2019-05-30 21:13:04.042 EDT [25137] LOG: database system is ready to accept connections2019-05-30 21:13:04.049 EDT [25145] LOG: cluster monitor started2019-05-30 21:13:04.020 EDT [2730] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:13:04.020 EDT [2730] LOG: listening on IPv6 address "::", port 54322019-05-30 21:13:04.021 EDT [2730] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:13:04.057 EDT [2731] LOG: database system was shut down at 2019-05-30 21:13:00 EDT2019-05-30 21:13:04.061 EDT [2730] LOG: database system is ready to accept connections2019-05-30 21:13:04.062 EDT [2738] LOG: cluster monitor startedDone.Initialize all the datanode masters.Initialize the datanode master datanode1.Initialize the datanode master datanode2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting all the datanode masters.Starting datanode master datanode1.Starting datanode master datanode2.2019-05-30 21:13:12.077 EDT [25392] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:13:12.077 EDT [25392] LOG: listening on IPv6 address "::", port 154322019-05-30 21:13:12.079 EDT [25392] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:13:12.114 EDT [25392] LOG: redirecting log output to logging collector process2019-05-30 21:13:12.114 EDT [25392] HINT: Future log output will appear in directory "pg_log".2019-05-30 21:13:12.079 EDT [2985] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:13:12.079 EDT [2985] LOG: listening on IPv6 address "::", port 154322019-05-30 21:13:12.081 EDT [2985] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:13:12.117 EDT [2985] LOG: redirecting log output to logging collector process2019-05-30 21:13:12.117 EDT [2985] HINT: Future log output will appear in directory "pg_log".Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done. 启动 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf start all 关闭 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf stop all 查看集群状态 [postgres@gtm ~]$ pgxc_ctl monitor all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlRunning: gtm masterRunning: coordinator master coord1Running: coordinator master coord2Running: datanode master datanode1Running: datanode master datanode2 配置集群信息 分别在数据节点、协调器节点上分别执行以下命令: 注:本节点只执行修改操作即可(alert node),其他节点执行创建命令(create node)。因为本节点已经包含本节点的信息。 create node coord1 with (type=coordinator,host=xl1, port=5432);create node coord2 with (type=coordinator,host=xl2, port=5432);alter node coord1 with (type=coordinator,host=xl1, port=5432);alter node coord2 with (type=coordinator,host=xl2, port=5432);create node datanode1 with (type=datanode, host=xl1,port=15432,primary=true,PREFERRED);create node datanode2 with (type=datanode, host=xl2,port=15432);alter node datanode1 with (type=datanode, host=xl1,port=15432,primary=true,PREFERRED);alter node datanode2 with (type=datanode, host=xl2,port=15432);select pgxc_pool_reload(); 分别登陆数据节点、协调器节点验证 postgres= select from pgxc_node;node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-----------+-----------+-----------+-----------+----------------+------------------+-------------coord1 | C | 5432 | xl1 | f | f | 1885696643coord2 | C | 5432 | xl2 | f | f | -1197102633datanode2 | D | 15432 | xl2 | f | f | -905831925datanode1 | D | 15432 | xl1 | t | f | 888802358(4 rows) 测试 插入数据 在数据节点1,执行相关操作。 通过协调器端口登录PG [postgres@xl1 ~]$ psql -p 5432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= create database lei;CREATE DATABASEpostgres= \c lei;You are now connected to database "lei" as user "postgres".lei= create table test1(id int,name text);CREATE TABLElei= insert into test1(id,name) select generate_series(1,8),'测试';INSERT 0 8lei= select from test1;id | name----+------1 | 测试2 | 测试5 | 测试6 | 测试8 | 测试3 | 测试4 | 测试7 | 测试(8 rows) 注:默认创建的表为分布式表,也就是每个数据节点值存储表的部分数据。关于表类型具体说明,下面有说明。 通过15432端口登录数据节点,查看数据 有5条数据 [postgres@xl1 ~]$ psql -p 15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= \c lei;You are now connected to database "lei" as user "postgres".lei= select from test1;id | name----+------1 | 测试2 | 测试5 | 测试6 | 测试8 | 测试(5 rows) 登录到节点2,查看数据 有3条数据 [postgres@xl2 ~]$ psql -p15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= \c lei;You are now connected to database "lei" as user "postgres".lei= select from test1;id | name----+------3 | 测试4 | 测试7 | 测试(3 rows) 两个节点的数据加起来整个8条,没有问题。 至此Postgre-XL集群搭建完成。 创建数据库、表时可能会出现以下错误: ERROR: Failed to get pooled connections 是因为pg_hba.conf配置不对,所有节点加上host all all 192.168.20.0/0 trust并重启集群即可。 ERROR: No Datanode defined in cluster 首先确认是否创建了数据节点,也就是create node相关的命令。如果创建了则执行select pgxc_pool_reload();使其生效即可。 集群管理与应用 表类型说明 REPLICATION表:各个datanode节点中,表的数据完全相同,也就是说,插入数据时,会分别在每个datanode节点插入相同数据。读数据时,只需要读任意一个datanode节点上的数据。 建表语法: CREATE TABLE repltab (col1 int, col2 int) DISTRIBUTE BY REPLICATION; DISTRIBUTE :会将插入的数据,按照拆分规则,分配到不同的datanode节点中存储,也就是sharding技术。每个datanode节点只保存了部分数据,通过coordinate节点可以查询完整的数据视图。 CREATE TABLE disttab(col1 int, col2 int, col3 text) DISTRIBUTE BY HASH(col1); 模拟数据插入 任意登录一个coordinate节点进行建表操作 [postgres@gtm ~]$ psql -h xl1 -p 5432 -U postgrespostgres= INSERT INTO disttab SELECT generate_series(1,100), generate_series(101, 200), 'foo';INSERT 0 100postgres= INSERT INTO repltab SELECT generate_series(1,100), generate_series(101, 200);INSERT 0 100 查看数据分布结果: DISTRIBUTE表分布结果 postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+-------1148549230 | 42-927910690 | 58(2 rows) REPLICATION表分布结果 postgres= SELECT count() FROM repltab;count -------100(1 row) 查看另一个datanode2中repltab表结果 [postgres@datanode2 pgxl9.5]$ psql -p 15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= SELECT count() FROM repltab;count -------100(1 row) 结论:REPLICATION表中,datanode1,datanode2中表是全部数据,一模一样。而DISTRIBUTE表,数据散落近乎平均分配到了datanode1,datanode2节点中。 新增数据节点与数据重分布 在线新增节点、并重新分布数据。 新增datanode节点 在gtm集群管理节点上执行pgxc_ctl命令 [postgres@gtm ~]$ pgxc_ctl/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.confFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlPGXC 在服务器xl3上,新增一个master角色的datanode节点,名称是datanode3 端口号暂定5430,pool master暂定6669 ,指定好数据目录位置,从两个节点升级到3个节点,之后要写3个none none应该是datanodeSpecificExtraConfig或者datanodeSpecificExtraPgHba配置PGXC add datanode master datanode3 xl3 15432 6671 /home/postgres/pgxc/nodes/datanode/datanode3 none none none 等待新增完成后,查询集群节点状态: postgres= select from pgxc_node;node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-----------+-----------+-----------+-----------+----------------+------------------+-------------datanode1 | D | 15432 | xl1 | t | f | 888802358datanode2 | D | 15432 | xl2 | f | f | -905831925datanode3 | D | 15432 | xl3 | f | f | -705831925coord1 | C | 5432 | xl1 | f | f | 1885696643coord2 | C | 5432 | xl2 | f | f | -1197102633(4 rows) 节点新增完毕 数据重新分布 由于新增节点后无法自动完成数据重新分布,需要手动操作。 DISTRIBUTE表分布在了node1,node2节点上,如下: postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+-------1148549230 | 42-927910690 | 58(2 rows) 新增一个节点后,将sharding表数据重新分配到三个节点上,将repl表复制到新节点 重分布sharding表postgres= ALTER TABLE disttab ADD NODE (datanode3);ALTER TABLE 复制数据到新节点postgres= ALTER TABLE repltab ADD NODE (datanode3);ALTER TABLE 查看新的数据分布: postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+--------700122826 | 36-927910690 | 321148549230 | 32(3 rows) 登录datanode3(新增的时候,放在了xl3服务器上,端口15432)节点查看数据: [postgres@gtm ~]$ psql -h xl3 -p 15432 -U postgrespsql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= select count() from repltab;count -------100(1 row) 很明显,通过 ALTER TABLE tt ADD NODE (dn)命令,可以将DISTRIBUTE表数据重新分布到新节点,重分布过程中会中断所有事务。可以将REPLICATION表数据复制到新节点。 从datanode节点中回收数据 postgres= ALTER TABLE disttab DELETE NODE (datanode3);ALTER TABLEpostgres= ALTER TABLE repltab DELETE NODE (datanode3);ALTER TABLE 删除数据节点 Postgresql-XL并没有检查将被删除的datanode节点是否有replicated/distributed表的数据,为了数据安全,在删除之前需要检查下被删除节点上的数据,有数据的话,要回收掉分配到其他节点,然后才能安全删除。删除数据节点分为四步骤: 1.查询要删除节点dn3的oid postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id -------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11819 | coord1 | C | 5432 | datanode1 | f | f | 188569664316384 | coord2 | C | 5432 | datanode2 | f | f | -119710263316385 | node1 | D | 5433 | datanode1 | f | t | 114854923016386 | node2 | D | 5433 | datanode2 | f | f | -92791069016397 | dn3 | D | 5430 | datanode1 | f | f | -700122826(5 rows) 2.查询dn3对应的oid中是否有数据 testdb= SELECT FROM pgxc_class WHERE nodeoids::integer[] @> ARRAY[16397];pcrelid | pclocatortype | pcattnum | pchashalgorithm | pchashbuckets | nodeoids ---------+---------------+----------+-----------------+---------------+-------------------16388 | H | 1 | 1 | 4096 | 16397 16385 1638616394 | R | 0 | 0 | 0 | 16397 16385 16386(2 rows) 3.有数据的先回收数据 postgres= ALTER TABLE disttab DELETE NODE (dn3);ALTER TABLEpostgres= ALTER TABLE repltab DELETE NODE (dn3);ALTER TABLEpostgres= SELECT FROM pgxc_class WHERE nodeoids::integer[] @> ARRAY[16397];pcrelid | pclocatortype | pcattnum | pchashalgorithm | pchashbuckets | nodeoids ---------+---------------+----------+-----------------+---------------+----------(0 rows) 4.安全删除dn3 PGXC$ remove datanode master dn3 clean 故障节点FAILOVER 1.查看当前集群状态 [postgres@gtm ~]$ psql -h xl1 -p 5432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11739 | coord1 | C | 5432 | xl1 | f | f | 188569664316384 | coord2 | C | 5432 | xl2 | f | f | -119710263316387 | datanode2 | D | 15432 | xl2 | f | f | -90583192516388 | datanode1 | D | 15432 | xl1 | t | t | 888802358(4 rows) 2.模拟datanode1节点故障 直接关闭即可 PGXC stop -m immediate datanode master datanode1Stopping datanode master datanode1.Done. 3.测试查询 只要查询涉及到datanode1上的数据,那么该查询就会报错 postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;WARNING: failed to receive file descriptors for connectionsERROR: Failed to get pooled connectionsHINT: This may happen because one or more nodes are currently unreachable, either because of node or network failure.Its also possible that the target node may have hit the connection limit or the pooler is configured with low connections.Please check if all nodes are running fine and also review max_connections and max_pool_size configuration parameterspostgres= SELECT xc_node_id, FROM disttab WHERE col1 = 3;xc_node_id | col1 | col2 | col3------------+------+------+-------905831925 | 3 | 103 | foo(1 row) 测试发现,查询范围如果涉及到故障的node1节点,会报错,而查询的数据范围不在node1上的话,仍然可以查询。 4.手动切换 要想切换,必须要提前配置slave节点。 PGXC$ failover datanode node1 切换完成后,查询集群 postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id -------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11819 | coord1 | C | 5432 | datanode1 | f | f | 188569664316384 | coord2 | C | 5432 | datanode2 | f | f | -119710263316386 | node2 | D | 15432 | datanode2 | f | f | -92791069016385 | node1 | D | 15433 | datanode2 | f | t | 1148549230(4 rows) 发现datanode1节点的ip和端口都已经替换为配置的slave了。 本篇文章为转载内容。原文链接:https://blog.csdn.net/qianglei6077/article/details/94379331。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-30 11:09:03
94
转载
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
pgrep process_name
- 查找与进程名匹配的进程ID。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
2023-04-28
2023-08-09
2023-06-18
2023-04-14
2023-02-18
2023-04-17
2024-01-11
2023-10-03
2023-09-09
2023-06-13
2023-08-07
2023-03-11
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"