前端技术
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
[ClickHouse 备份恢复工具 cl...]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
ClickHouse
如何处理ClickHouse中的数据丢失问题? 在大数据时代,ClickHouse作为一款高性能的列式数据库管理系统,在实时分析、在线查询等领域有着广泛的应用。然而,在实际用起来的时候,由于各种乱七八糟的原因,比如硬件出毛病了、网络突然掉链子啦,甚至有时候咱们自己手滑操作失误,都可能让ClickHouse里面的数据不翼而飞。本文将探讨如何有效预防和处理这类问题,让你的数据安全更有保障。 1. 数据备份与恢复 1.1 定期备份 防止数据丢失的第一道防线是定期备份。ClickHouse提供了backup命令行工具来进行数据备份: bash clickhouse-backup create backup_name 这条命令会将当前集群的所有数据进行全量备份,并保存到指定目录。你还可以通过配置文件或命令行参数指定要备份的具体数据库或表。 1.2 恢复备份 当发生数据丢失时,可以利用备份文件进行恢复: bash clickhouse-backup restore backup_name 执行上述命令后,ClickHouse将会从备份中恢复所有数据。千万要注意啊,伙计,在你动手进行恢复操作之前,得先瞧瞧目标集群是不是空空如也,或者你是否能接受数据被覆盖这个可能的结果。 2. 使用Replication(复制)机制 2.1 配置Replicated表 ClickHouse支持ZooKeeper或Raft协议实现的多副本复制功能。例如,创建一个分布式且具有复制特性的表: sql CREATE TABLE replicated_table ( ... ) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{database}/{table}', 'replica1') PARTITION BY ... ORDER BY ... 这里,/clickhouse/tables/{database}/{table}是一个 ZooKeeper 路径,用于协调多个副本之间的数据同步;'replica1'则是当前副本标识符。 2.2 数据自动同步与容灾 一旦某台服务器上的数据出现异常,其他拥有相同Replicated表的服务器仍保留完整的数据。当有新的服务器小弟加入集群大家庭,或者主节点大哥不幸挂掉的时候,Replication机制这个超级替补队员就会立马出动,自动把数据同步得妥妥的,确保所有数据都能保持一致性、完整性,一个字都不会少。 3. 数据一致性检查与修复 3.1 使用checksum函数 ClickHouse提供checksum函数来计算表数据的校验和,可用于验证数据是否完整: sql SELECT checksum() FROM table_name; 定期执行此操作并记录结果,以便在后续时间点对比校验和的变化,从而发现可能的数据丢失问题。 3.2 表维护及修复 若发现数据不一致,可以尝试使用OPTIMIZE TABLE命令进行表维护和修复: sql OPTIMIZE TABLE table_name FINAL; 该命令会重新整理表数据,并尝试修复任何可能存在的数据损坏问题。 4. 实践思考与探讨 尽管我们可以通过上述方法来减少和应对ClickHouse中的数据丢失风险,但防患于未然总是最优策略。在搭建和运用ClickHouse系统的时候,千万记得要考虑让它“坚如磐石”,也就是要设计出高可用性方案。比如说,我们可以采用多副本这种方式,就像备份多个小帮手一样,让数据安全无忧;再者,跨地域冗余存储也是一招妙计,想象一下,即使地球另一边的机房挂了,这边的数据也能照常运作,这样就大大提升了系统的稳健性和可靠性啦!同时,建立一个完善、接地气的数据监控系统,能够灵敏捕捉并及时解决那些可能冒头的小问题,这绝对是一个无比关键的步骤。 总结起来,面对ClickHouse数据丢失问题,我们需采取主动防御和被动恢复相结合的方式,既要做好日常的数据备份和Replication配置,也要学会在问题发生后如何快速有效地恢复数据,同时结合数据一致性检查以及表维护等手段,全面提升数据的安全性和稳定性。在实践中不断优化和完善,才能真正发挥出ClickHouse在海量数据分析领域的强大威力。
2023-01-20 13:30:03
445
月影清风
ClickHouse
ClickHouse:系统重启与数据丢失的探讨 1. 引言 --- 当我们谈论ClickHouse这款高性能列式数据库管理系统时,其出色的查询速度和处理大数据的能力往往让我们赞不绝口。然而,在实际使用过程中,我们也可能会遇到一些棘手的问题,比如系统突然重启导致的数据丢失。嘿,朋友,这篇文章要带你一起揭开这个问题的神秘面纱,咱们会通过实实在在的代码实例,手把手探讨在ClickHouse这个家伙里头如何巧妙躲开这类问题,还有配套的解决方案,保证让你收获满满! 2. 系统重启对ClickHouse的影响 --- 首先,我们需要明确一点:ClickHouse本身具备极高的稳定性,并且设计了日志持久化机制以保证数据安全。就像你用笔记本记事那样,如果在你还没来得及把重要事情完全写下来,或者字迹还没干的时候,突然有人把本子合上了,那这事儿可能就找不回来了。同样道理,任何一个数据库系统,假如在它还没彻底完成保存数据或者数据还在半空中没安稳落地的时候,系统突然重启了,那就确实有可能会让这些数据消失得无影无踪。这是因为ClickHouse为了飙出最顶级的性能,到了默认配置这一步,它并不急着把所有的数据立马同步到磁盘上,而是耍了个小聪明——用上了异步刷盘这一招。 3. 数据丢失案例分析与代码示例 --- 假设我们正在向ClickHouse表中插入一批数据: sql -- 插入大量数据到ClickHouse表 INSERT INTO my_table (column1, column2) VALUES ('data1', 'value1'), ('data2', 'value2'), ...; 若在这批数据还未完全落盘时,系统意外重启,则未持久化的数据可能会丢失。 为了解决这个问题,ClickHouse提供了insert_quorum、select_sequential_consistency等参数来保障数据的一致性和可靠性: sql -- 使用insert_quorum确保数据在多数副本上成功写入 INSERT INTO my_table (column1, column2) VALUES ('data1', 'value1') SETTINGS insert_quorum = 2; -- 或者启用select_sequential_consistency确保在查询时获取的是已持久化的最新数据 SELECT FROM my_table SETTINGS select_sequential_consistency = 1; 4. 防止数据丢失的策略 --- - 设置合理的写入一致性级别:如上述示例所示,通过调整insert_quorum参数可以设定在多少个副本上成功写入后才返回成功,从而提高数据安全性。 - 启用同步写入模式:尽管这会牺牲一部分性能,但在关键场景下可以通过修改mutations_sync、fsync_after_insert等配置项强制执行同步写入,确保每次写入操作完成后数据都被立即写入磁盘。 - 定期备份与恢复策略:不论何种情况,定期备份都是防止数据丢失的重要手段。利用ClickHouse提供的备份工具如clickhouse-backup,可以实现全量和增量备份,结合云存储服务,即使出现极端情况也能快速恢复数据。 5. 结语 人类智慧与技术融合 --- 面对“系统重启导致数据丢失”这一问题,我们在惊叹ClickHouse强大功能的同时,也需理性看待并积极应对潜在风险。作为用户,我们可不能光有硬邦邦的技术底子,更重要的是得有个“望远镜”,能预见未来,摸透并活学活用各种骚操作和神器,让ClickHouse这个小哥更加贴心地服务于咱们的业务需求,让它成为咱的好帮手。毕竟,数据库管理不只是冰冷的代码执行,更是我们对数据价值理解和尊重的体现,是技术与人类智慧碰撞出的璀璨火花。
2023-08-27 18:10:07
602
昨夜星辰昨夜风
Oracle
...cle数据库如何进行备份和恢复策略的制定和管理? 随着信息化时代的不断发展,企业的核心业务系统越来越依赖于数据库系统,数据库的安全性和稳定性成为保障企业正常运营的关键因素之一。其中,数据库备份和恢复策略的制定和管理尤为重要。接下来,咱要从几个关键点入手,手把手教你咋在Oracle数据库里头规划并打理好备份和恢复这套流程,保证让你明明白白、清清楚楚。 一、备份和恢复策略的重要性 首先,我们需要明确备份和恢复策略的重要性。在日常使用数据库的时候,你可能遇到各种意想不到的情况,比如说硬件突然闹脾气出故障啦,人为操作不小心马失前蹄犯了错误啦,甚至有时候老天爷不赏脸来场自然灾害啥的,这些都有可能让咱们辛辛苦苦存的数据一下子消失得无影无踪。这样一来,企业的正常运作可就要受到不小的影响了,你说是不是?所以呢,咱们得养成定期给数据库做备份的好习惯,而且得有一套既科学又合理的备份和恢复方案。这样,一旦哪天出了岔子,咱们就能迅速、有效地把数据恢复过来,不至于让损失进一步扩大。 二、备份和恢复策略的制定 接下来,我们来详细介绍一下如何在Oracle数据库中制定备份和恢复策略。一般来说,备份和恢复策略主要包括以下内容: 1. 备份频率 根据数据库的重要性、数据更新频率等因素,确定备份的频率。对于重要且频繁更新的数据库,建议每天至少进行一次备份。 2. 备份方式 备份方式主要有全备份、增量备份和差异备份等。全备份是对数据库进行全面的备份,增量备份是对上次备份后的新增数据进行备份,差异备份是对上次全备份后至本次备份之间的变化数据进行备份。选择合适的备份方式可以有效减少备份时间和存储空间。 3. 存储备份 存储备份的方式主要有磁盘存储、网络存储和云存储等。选择合适的存储方式可以保证备份的可靠性和安全性。 4. 恢复测试 为了确保备份的有效性,需要定期进行恢复测试,检查备份数据是否完整,恢复操作是否正确。 三、备份和恢复策略的执行 有了备份和恢复策略之后,我们需要如何执行呢?下面我们就来看看具体的操作步骤: 1. 使用RMAN工具进行备份和恢复 RMAN是Oracle自带的备份恢复工具,可以方便地进行全备份、增量备份和差异备份,支持本地备份和远程备份等多种备份方式。 例如,我们可以使用以下命令进行全备份: csharp rman target / catalog ; backup database; 2. 手动进行备份和恢复 除了使用RMAN工具外,我们还可以手动进行备份和恢复。具体的步骤如下: a. 进行全备份:使用以下命令进行全备份: go expdp owner/ directory= dumpfile=; b. 进行增量备份:使用以下命令进行增量备份: csharp impdp owner/ directory= dumpfile=; c. 进行恢复:使用以下命令进行恢复: bash spool recovery.log rman target / catalog ; recover datafile ; spool off; 四、备份和恢复策略的优化 最后,我们再来讨论一下如何优化备份和恢复策略。备份和恢复策略的优化主要涉及到以下几点: 1. 减少备份时间 可以通过增加并行度、使用更高效的压缩算法等方式减少备份时间。 2. 提高备份效率 可以通过合理设置备份策略、选择合适的存储设备等方式提高备份效率。 3. 提升数据安全性 可以通过加密备份数据、设置备份权限等方式提升数据安全性。 总结来说,备份和恢复策略的制定和管理是一项复杂而又重要的工作,我们需要充分考虑备份的频率、方式、存储和恢复等多个方面的因素,才能够制定出科学合理的备份和恢复策略,从而确保数据库的安全性和稳定性。同时呢,我们也要持续地改进和调整我们的备份与恢复方案,好让它能紧跟业务需求和技术环境的不断变化步伐。
2023-05-03 11:21:50
112
诗和远方-t
Greenplum
...然而,即使是最强大的工具也会出现问题。让我们一起探索一下为什么会出现这种情况,以及如何解决这个问题。 2. 原因分析 2.1 硬件故障 硬件故障是导致数据文件完整性检查失败的常见原因。硬盘要是罢工了,电源突然玩消失,或者网络抽风出故障,都有可能让你的数据说拜拜,这样一来,完整性检查自然也就没法顺利进行了。 sql SELECT FROM gp_toolkit.gp_inject_fault('gp_segment_host', 'random_io_error', 1, true); 这段代码将模拟随机IO错误,从而模拟硬件故障的情况。我们可以通过这种方式来测试我们的数据恢复机制。 2.2 系统错误 系统错误也可能导致数据文件完整性检查失败。比如,操作系统要是突然罢工了,或者进程卡壳不动弹了,这就可能会让还没完成的数据操作给撂挑子,这样一来,完整性检查也就难免会受到影响啦。 sql kill -9 ; 这段代码将杀死指定PID的进程。我们可以使用这种方式来模拟系统错误。 2.3 用户错误 用户错误也是导致数据文件完整性检查失败的一个重要原因。比如,假如用户手滑误删了关键数据,或者不留神改错了数据结构,那么完整性校验这一关就过不去啦。 sql DELETE FROM my_table; 这段代码将删除my_table中的所有记录。我们可以使用这种方式来模拟用户错误。 3. 解决方案 3.1 备份与恢复 为了防止数据丢失,我们需要定期备份数据,并且要确保备份是完整的。一旦发生数据文件完整性检查失败,我们可以从备份中恢复数据。 sql pg_dumpall > backup.sql 这段代码将备份整个数据库到backup.sql文件中。我们可以使用这个文件来恢复数据。 3.2 系统监控 通过系统监控,我们可以及时发现并解决问题。比如,假如我们瞅见某个家伙的CPU占用率爆表了,那咱就得琢磨琢磨,是不是这家伙的硬件出啥幺蛾子了。 sql SELECT datname, pg_stat_activity.pid, state, query FROM pg_stat_activity WHERE datname = ''; 这段代码将显示当前正在运行的所有查询及其状态。我们可以根据这些信息来判断是否存在异常情况。 3.3 用户培训 最后,我们应该对用户进行培训,让他们了解正确的使用方法,避免因为误操作而导致的数据文件完整性检查失败。 sql DO $$ BEGIN RAISE NOTICE 'INSERT INTO my_table VALUES (1, 2)'; EXCEPTION WHEN unique_violation THEN RAISE NOTICE 'Error: INSERT failed'; END$$; 这段代码将在my_table表中插入一条新的记录。我们可以使用这个例子来教给用户如何正确地插入数据。 4. 结论 数据文件完整性检查失败是一个严重的问题,但我们并不需要害怕它。只要我们掌握了正确的知识和技能,就能够有效地应对这个问题。 通过本文的学习,你应该已经知道了一些可能导致数据文件完整性检查失败的原因,以及一些解决方案。希望这篇文章能够帮助你在遇到问题时找到正确的方向。
2023-12-13 10:06:36
529
风中飘零-t
SeaTunnel
...unnel中实现数据备份与恢复功能? SeaTunnel(原名Waterdrop)是一款开源、易用且高效的大数据集成工具,它支持从各种数据源抽取数据并进行实时或批处理,同时具备丰富的转换和加载能力。在这篇文章里,咱们就手拉手一起深入探究一下,如何像平常给手机照片做备份防止丢失那样,灵活运用SeaTunnel这个小工具来搞定数据备份与恢复的大问题吧! 1. SeaTunnel基础理解 首先,我们需要对SeaTunnel的核心概念有所了解。在SeaTunnel的世界里,一切操作围绕着“source”(数据源)、“transform”(数据转换)和“sink”(数据目的地)这三个核心模块展开。想象一下,数据如同水流,从源头流出,经过一系列的过滤和转化,最终流向目标水库。 yaml SeaTunnel配置示例 mode: batch 数据源配置 source: type: mysql jdbcUrl: "jdbc:mysql://localhost:3306/test" username: root password: password table: my_table 数据转换(这里暂时为空,但实际可以用于清洗、去重等操作) transforms: 数据目的地(备份到另一个MySQL数据库或HDFS等存储系统) sink: type: mysql jdbcUrl: "jdbc:mysql://backup-server:3306/backup_test" username: backup_root password: backup_password table: backup_my_table 2. 数据备份功能实现 对于数据备份,我们可以将SeaTunnel配置为从生产环境的数据源读取数据,并将其写入到备份存储系统。例如,从MySQL数据库中抽取数据,并存入到另一台MySQL服务器或者HDFS、S3等大数据存储服务: yaml 备份数据到另一台MySQL服务器 sink: type: mysql ... 或者备份数据到HDFS sink: type: hdfs path: /backup/data/ file_type: text 在此过程中,你可以根据业务需求设置定期备份任务,确保数据的实时性和一致性。 3. 数据恢复功能实现 当需要进行数据恢复时,SeaTunnel同样可以扮演关键角色。通过修改配置文件,将备份数据源替换为目标系统的数据源,并重新执行任务,即可完成数据的迁移和恢复。 yaml 恢复数据到原始MySQL数据库 source: type: mysql 这里的配置应指向备份数据所在的MySQL服务器及表信息 sink: type: mysql 这里的配置应指向要恢复数据的目标MySQL服务器及表信息 4. 实践中的思考与探讨 在实际使用SeaTunnel进行数据备份和恢复的过程中,我们可能会遇到一些挑战,如数据量大导致备份时间过长、网络状况影响传输效率等问题。这就需要我们根据实际情况,像变戏法一样灵活调整我们的备份策略。比如说,我们可以试试增量备份这个小妙招,只备份新增或改动的部分,就像给文件更新打个小补丁;或者采用压缩传输的方式,把数据“挤一挤”,让它们更快更高效地在网路上跑起来,这样就能让整个流程更加顺滑、更接地气儿啦。 此外,为了保证数据的一致性,在执行备份或恢复任务时,还需要考虑事务隔离、并发控制等因素,以避免因并发操作引发的数据不一致问题。在SeaTunnel这个工具里头,我们能够借助它那牛哄哄的插件系统和超赞的扩展性能,随心所欲地打造出完全符合自家业务需求的数据备份与恢复方案,就像是量体裁衣一样贴合。 总之,借助SeaTunnel,我们能够轻松实现大规模数据的备份与恢复,保障业务连续性和数据安全性。在实际操作中不断尝试、改进,我坚信你一定能亲手解锁更多SeaTunnel的隐藏实力,让这个工具变成企业数据安全的强大守护神,稳稳地护航你的数据安全。
2023-04-08 13:11:14
114
雪落无痕
转载文章
...qldump这一强大工具的基础使用方法和选项后,进一步了解数据库备份与恢复的策略以及行业内的最新进展显得尤为重要。近期,MySQL 8.0版本对mysqldump功能进行了增强,新增了并行导出多个表的能力,显著提升了大数据量场景下的备份效率(来源:MySQL官方文档,2023年更新)。对于企业级用户来说,结合云存储服务实现自动化、周期性的mysqldump备份任务已成为标准实践,例如阿里云RDS就提供了基于mysqldump的全量与增量备份方案。 此外,数据安全在备份过程中是不可忽视的一环。《InfoWorld》杂志在一篇深度报道中指出,尽管mysqldump具备众多实用选项,但在处理包含敏感信息的大规模数据库时,建议采用加密传输或配合SSL配置以确保数据在传输过程中的安全性。同时,也有专家提倡利用像Percona Xtrabackup这样的第三方工具进行物理备份,特别是在InnoDB存储引擎下,它能提供更细粒度的热备份与恢复操作。 另外值得注意的是,针对数据库性能优化,业界倡导将备份时间安排在业务低峰期,并结合缓存技术与索引调整等手段减少备份期间对在线服务的影响。随着容器化和Kubernetes等云原生技术的发展,如何在分布式环境下高效运用mysqldump进行数据迁移与灾备也成为IT专业人士关注的新课题。 综上所述,掌握mysqldump的基本操作仅仅是开始,不断跟进最新的数据库管理技术和最佳实践,深入理解和灵活应用不同备份恢复策略,才能确保在复杂多变的业务场景中,有效保障数据的安全性和系统的稳定性。
2023-02-01 23:51:06
265
转载
Oracle
...深入了解了数据库无法备份或恢复的常见原因与解决方案后,进一步关注数据库安全及数据保护领域的最新动态至关重要。近期,全球领先的云服务提供商AWS发布了全新的数据库备份与恢复功能升级,引入了实时连续备份和多版本恢复选项,极大地提升了用户在面临系统故障、硬件损坏或软件问题时的数据恢复能力。 同时,随着GDPR等数据保护法规的严格实施,企业对数据库安全性的重视程度达到了前所未有的高度。据Infosecurity Magazine报道,多家国际知名公司正积极采用AI驱动的数据库监控工具,实现对潜在威胁的预测性防护,并通过自动化审计和加密技术确保数据在备份过程中的安全性。 另外,在学术研究领域,《计算机科学》期刊最近发表了一篇深度分析文章,强调了数据库系统设计中容错机制的重要性,并提出了一种基于分布式存储和区块链技术的新型备份恢复策略,为未来提升数据库系统的稳定性和可靠性提供了新的理论指导和实践路径。 综上所述,无论是紧跟技术发展步伐,采用先进的数据库备份恢复技术,还是顺应法律法规要求强化数据安全措施,都是在应对数据库无法备份或恢复问题时需要持续关注和深入研究的重要方向。
2023-09-16 08:12:28
93
春暖花开-t
Apache Lucene
...理这种问题,包括如何备份索引文件、如何恢复丢失的索引文件以及如何移动索引文件等。 一、备份索引文件 备份索引文件是预防数据丢失的一种重要措施。我们完全可以时不时地把索引文件备份到其他位置,这样万一哪天需要了,就能迅速恢复过来,保证效率杠杠的。 以下是使用Apache Lucene备份索引文件的示例代码: java import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; // 打开索引目录 Directory directory = FSDirectory.open(new File("/path/to/index")); // 创建DirectoryReader DirectoryReader reader = DirectoryReader.open(directory); // 将索引目录转换为路径 Path path = Paths.get("/path/to/backup"); // 复制索引目录到备份路径 Files.copy(directory.toPath(), path); // 关闭DirectoryReader reader.close(); 二、恢复丢失的索引文件 如果索引文件丢失,我们可以尝试恢复它。在许多情况下,丢失的索引文件可能已经被包含在备份文件中。 以下是使用Apache Lucene恢复丢失的索引文件的示例代码: java import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; // 打开备份目录 Directory directory = FSDirectory.open(new File("/path/to/backup")); // 创建DirectoryReader DirectoryReader reader = DirectoryReader.open(directory); // 将备份目录转换为路径 Path path = Paths.get("/path/to/index"); // 复制备份目录到索引路径 Files.copy(directory.toPath(), path); // 关闭DirectoryReader reader.close(); 三、移动索引文件 如果我们需要将索引文件从一个位置移动到另一个位置,我们可以使用copyTo()方法将索引文件复制到新位置,然后关闭原始索引文件。 以下是使用Apache Lucene移动索引文件的示例代码: java import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; // 打开原始索引目录 Directory directory = FSDirectory.open(new File("/path/to/index")); // 创建DirectoryReader DirectoryReader reader = DirectoryReader.open(directory); // 获取索引目录的路径 Path oldPath = directory.toPath(); // 获取新索引目录的路径 Path newPath = Paths.get("/path/to/newindex"); // 使用copyTo()方法复制索引文件 directory.copyTo(new FSDirectory(newPath), oldPath); // 关闭DirectoryReader reader.close(); // 关闭原始索引文件 directory.close(); 以上就是关于如何处理“索引文件移动或丢失”问题的一些解决方案,希望对你有所帮助。最后我想唠叨一下,虽然Apache Lucene这款工具真是强大又灵活得不得了,但我们在使唤它的时候,千万可别忘了数据安全和备份这码事儿,要不然一不小心踩到坑里,那损失就太冤枉了。
2023-10-23 22:21:09
467
断桥残雪-t
HBase
...然而,即使是最强大的工具也可能会出现问题,就像HBase一样。在这篇文章里,我们打算聊聊一个大家可能都碰到过的问题——HBase表的数据有时候会在某个时间点神秘消失。 二、数据丢失的原因 在大数据世界里,数据丢失是一个普遍存在的问题,它可能是由于硬件故障、网络中断、软件错误或者人为操作失误等多种原因导致的。而在HBase中,数据丢失的主要原因是磁盘空间不足。当硬盘空间不够,没法再存新的数据时,HBase这个家伙就会动手干一件事:它会把那些陈年旧的数据块打上“已删除”的标签,并且把它们占用的地盘给腾出来,这样一来就空出地方迎接新的数据了。这种机制可以有效地管理磁盘空间,但同时也可能导致数据丢失。 三、如何防止数据丢失 那么,我们如何防止HBase表的数据在某个时间点上丢失呢?以下是一些可能的方法: 3.1 数据备份 定期对HBase数据进行备份是一种有效的防止数据丢失的方法。HBase提供了多种备份方式,包括物理备份和逻辑备份等。例如,我们可以使用HBase自带的Backup和Restore工具来创建和恢复备份。 java // 创建备份 hbaseShell.execute("backup table myTable to 'myBackupDir'"); // 恢复备份 hbaseShell.execute("restore table myTable from backup 'myBackupDir'"); 3.2 使用HFileSplitter HFileSplitter是HBase提供的一种用于分片和压缩HFiles的工具。通过分片,我们可以更有效地管理和备份HBase数据。例如,我们可以将一个大的HFile分割成多个小的HFiles,然后分别进行备份。 java // 分割HFile hbaseShell.execute("split myTable 'ROW_KEY_SPLITTER:CHUNK_SIZE'"); // 备份分片后的HFiles hbaseShell.execute("backup split myTable"); 四、总结 数据丢失是任何大数据系统都无法避免的问题,但在HBase中,通过合理的配置和正确的操作,我们可以有效地防止数据丢失。同时,咱们也得明白一个道理,就是哪怕咱们拼尽全力,也无法给数据的安全性打包票,做到万无一失。所以,当我们用HBase时,最好能培养个好习惯,定期给数据做个“体检”和“备胎”,这样万一哪天它闹情绪了,咱们也能快速让它满血复活。 五、参考文献 [1] Apache HBase官方网站:https://hbase.apache.org/ [2] HBase Backup and Restore Guide:https://hbase.apache.org/book.html_backup_and_restore [3] HFile Splitter Guide:https://hbase.apache.org/book.html_hfile_splitter
2023-08-27 19:48:31
414
海阔天空-t
ClickHouse
...话说在这个大环境下,ClickHouse闪亮登场啦!它可是一款超级厉害的数据库系统,采用了列式存储的方式,嗖嗖地提升查询速度,延迟低到让你惊讶。这一特性瞬间就吸引了无数开发者和企业的眼球,大家都对它青睐有加呢! 二、ClickHouse的特性 ClickHouse的特点主要体现在以下几个方面: 1. 高性能 ClickHouse通过独特的列式存储方式和计算引擎,实现了极致的查询性能,对于实时查询和复杂分析场景有着显著的优势。 2. 稳定性 ClickHouse具有良好的稳定性,能够支持大规模的数据处理和分析,并且能够在分布式环境下提供高可用的服务。 3. 易用性 ClickHouse提供了直观易用的SQL接口,使得数据分析变得更加简单和便捷。 三、使用ClickHouse实现高可用性架构 1. 什么是高可用性架构? 所谓高可用性架构,就是指一个系统能够在出现故障的情况下,仍能继续提供服务,保证业务的连续性和稳定性。在实际应用中,我们通常会采用冗余、负载均衡等手段来构建高可用性架构。 2. 如何使用ClickHouse实现高可用性架构? (1) 冗余部署 我们可以将多个ClickHouse服务器进行冗余部署,当某个服务器出现故障时,其他服务器可以接管其工作,保证服务的持续性。比如说,我们可以动手搭建一个ClickHouse集群,这个集群里头有三个节点。具体咋安排呢?两个节点咱们让它担任主力,也就是主节点的角色;剩下一个节点呢,就作为备胎,也就是备用节点,随时待命准备接替工作。 (2) 负载均衡 通过负载均衡器,我们可以将用户的请求均匀地分发到各个ClickHouse服务器上,避免某一台服务器因为承受过大的压力而出现性能下降或者故障的情况。比如,我们可以让Nginx大显身手,充当一个超级智能的负载均衡器。想象一下,当请求像潮水般涌来时,Nginx这家伙能够灵活运用各种策略,比如轮询啊、最少连接数这类玩法,把请求均匀地分配到各个服务器上,保证每个服务器都能忙而不乱地处理任务。 (3) 数据备份和恢复 为了防止因数据丢失而导致的问题,我们需要定期对ClickHouse的数据进行备份,并在需要时进行恢复。例如,我们可以使用ClickHouse的内置工具进行数据备份,然后在服务器出现故障时,从备份文件中恢复数据。 四、代码示例 下面是一个简单的ClickHouse查询示例: sql SELECT event_date, SUM(event_count) as total_event_count FROM events GROUP BY event_date; 这个查询语句会统计每天的事件总数,并按照日期进行分组。虽然ClickHouse在查询速度上确实是个狠角色,但当我们要对付海量数据的时候,还是得悠着点儿,注意优化查询策略。就拿那些不必要的JOIN操作来说吧,能省则省;还有索引的使用,也得用得恰到好处,才能让这个高性能的家伙更好地发挥出它的实力来。 五、总结 ClickHouse是一款功能强大的高性能数据库系统,它为我们提供了构建高可用性架构的可能性。不过呢,实际操作时咱们也要留心,挑对数据库系统只是第一步,更关键的是,得琢磨出一套科学合理的架构设计方案,还得写出那些快如闪电的查询语句。只有这样,才能确保系统的稳定性与高效性,真正做到随叫随到、性能杠杠滴。
2023-06-13 12:31:28
558
落叶归根-t
Hive
...除或覆盖的应对策略及恢复方法 1. 引言 在大数据处理领域,Apache Hive作为一款基于Hadoop的数据仓库工具,以其SQL-like查询能力和大规模数据处理能力深受广大开发者喜爱。然而,在平时我们管理维护的时候,常常会遇到一个让人挠破头皮的头疼问题:就是Hive表里的数据可能突然就被误删或者不小心被覆盖了。这篇文章会手把手地带你钻进这个问题的最深处,咱们通过一些实实在在的代码例子,一起聊聊怎么防止这类问题的发生,再讲讲万一真碰上了,又该采取哪些恢复措施来“救火”。 2. Hive表数据丢失的风险与原因 常见的Hive表数据丢失的情况通常源于误操作,例如错误地执行了DROP TABLE、TRUNCATE TABLE或者INSERT OVERWRITE等命令。这些操作可能在一瞬间让积累已久的数据化为乌有,让人懊悔不已。因此,理解和掌握避免这类风险的方法至关重要。 3. 预防措施 备份与版本控制 示例1: sql -- 创建Hive外部表并指向备份数据目录 CREATE EXTERNAL TABLE backup_table LIKE original_table LOCATION '/path/to/backup/data'; -- 将原始数据定期导出到备份表 INSERT INTO TABLE backup_table SELECT FROM original_table; 通过创建外部表的方式进行定期备份,即使原始数据遭到破坏,也能从备份中快速恢复。此外,要是把版本控制系统(比如Git)运用在DDL脚本的管理上,那就等于给咱们的数据结构和历史变更上了双保险,让它们的安全性妥妥地更上一层楼。 4. 数据恢复策略 示例2: sql -- 如果是由于DROP TABLE导致数据丢失 -- 可以先根据备份重新创建表结构 CREATE TABLE original_table LIKE backup_table; -- 然后从备份表中还原数据 INSERT INTO TABLE original_table SELECT FROM backup_table; 示例3: sql -- 如果是INSERT OVERWRITE导致部分或全部数据被覆盖 -- 则需要根据备份数据,定位到覆盖前的时间点 -- 然后使用相同方式恢复该时间点的数据 INSERT INTO TABLE original_table SELECT FROM backup_table WHERE timestamp_column <= 'overwrite_time'; 5. 深入思考与优化方案 在面对Hive表数据丢失的问题时,我们的首要任务是保证数据安全和业务连续性。除了上述的基础备份恢复措施,还可以考虑更高级的解决方案,比如: - 使用ACID事务特性(Hive 3.x及以上版本支持)来增强数据一致性,防止并发写入造成的数据冲突和覆盖。 - 结合HDFS的快照功能实现增量备份,提高数据恢复效率。 - 对关键操作实施权限管控和审计,减少人为误操作的可能性。 6. 结论 面对Hive表数据意外删除或覆盖的困境,人类的思考过程始终围绕着预防和恢复两大主题。你知道吗,就像给宝贝东西找个安全的保险箱一样,我们通过搭建一套给力的数据备份系统,把规矩立得明明白白的操作流程严格执行起来,再巧用Hive这些高科技工具的独特优势,就能把数据丢失的可能性降到最低,这样一来,甭管遇到啥突发状况,我们都能够淡定应对,稳如泰山啦!记住,数据安全无小事,每一次的操作都值得我们审慎对待。
2023-07-14 11:23:28
787
凌波微步
转载文章
...化效果: 根据微信的实践,调整配置项后,损坏率可以降低一半,但并不能完全避免损坏,所以我们还是需要补救措施。 补救措施: 通过查阅 SQLite 的相关资料,发现修复损坏数据库的两种思路和四种方案。 思路一:数据导出 .dump修复 从 master 表中读出一个个表的信息,根据根节点地址和创表语句来 select 出表里的数据,能 select 多少是多少,然后插入到一个新 DB 中。 每个SQLite DB都有一个sqlite_master表,里面保存着全部table和index的信息(table本身的信息,不包括里面的数据哦),遍历它就可以得到所有表的名称和 CREATE TABLE ...的SQL语句,输出CREATE TABLE语句,接着使用SELECT FROM ... 通过表名遍历整个表,每读出一行就输出一个INSERT语句,遍历完后就把整个DB dump出来了。 这样的操作,和普通查表是一样的,遇到损坏一样会返回SQLITE_CORRUPT,我们忽略掉损坏错误, 继续遍历下个表,最终可以把所有没损坏的表以及损坏了的表的前半部分读取出来。将 dump 出来的SQL语句逐行执行,最终可以得到一个等效的新DB。 思路二:数据备份 拷贝: 不能再直白的方式。由于SQLite DB本身是文件(主DB + journal 或 WAL), 直接把文件复制就能达到备份的目的。 .dump备份: 上一个恢复方案用到的命令的本来目的。在DB完好的时候执行.dump, 把 DB所有内容输出为 SQL语句,达到备份目的,恢复的时候执行SQL即可。 Backup API: SQLite自身提供的一套备份机制,按 Page 为单位复制到新 DB, 支持热备份。 综合思路:备份master表+数据导出 WCDB框架: 数据库完整时备份master表,数据库损坏时通过使用已备份的master表读取损坏数据库来恢复数据。成功率大概是70%。缺点在于我们目前项目使用的是CoreData框架,迁移成本非常的高。没有办法使用。 补救措施选型原则: 这么多的方案孰优孰劣?作为一个移动APP,我们追求的就是用户体验,根据资料推断只有万分之一不到的用户会发生DB损坏,不能为了极个别牺牲全体用户的体验。不影响用户体验的方法就是好方案。主要考量指标如下: 一:恢复成功率 由于牵涉到用户核心数据,“姑且一试”的方案是不够的,虽说 100% 成功率不太现实,但 90% 甚至 99% 以上的成功率才是我们想要的。 二:备份大小: 原本用户就可能有2GB 大的 DB,如果备份数据本身也有2GB 大小,用户想必不会接受。 三:备份性能: 性能则主要影响体验和备份成功率,作为用户不感知的功能,占用太多系统资源造成卡顿 是不行的,备份耗时越久,被系统杀死等意外事件发生的概率也越高。 数据导出方案考量: 恢复成功率大概是30%。不需要事先备份,故备份大小和备份性能都是最优的。 备份方案考量: 备份方案的理论恢复成功率都为100%,需要考量的即为备份大小和性能。 拷贝:备份大小等于原文件大小。备份性能最好,直接拷贝文件,不需要运算。 Backup API: 备份大小等于原文件大小。备份性能最差,原因是热备份,需要用到锁机制。 .dump:因为重新进行了排序,备份大小小于原文件。备份性能居中,需要遍历数据库生成语句。 可以看出,比较折中的选择是 Dump ,备份大小具有明显优势,备份性能尚可,恢复性能较差但由于需要恢复的场景较少,算是可以接受的短板。 深入钻研 即使优化后的方案,对于大DB备份也是耗时耗电,对于移动APP来说,可能未必有这样的机会做这样重度的操作,或者频繁备份会导致卡顿和浪费使用空间。 备份思路的高成本迫使我们从另外的方案考虑,于是我们再次把注意力放在之前的Dump方案。 Dump 方案本质上是尝试从坏DB里读出信息,这个尝试一般来说会出现两种结果: DB的基本格式仍然健在,但个别数据损坏,读到损坏的地方SQLite返回SQLITE_CORRUPT错误, 但已读到的数据得以恢复。 基本格式丢失(文件头或sqlite_master损坏),获取有哪些表的时候就返回SQLITE_CORRUPT, 根本没法恢复。 第一种可以算是预期行为,毕竟没有损坏的数据能部分恢复。从成功率来看,不少用户遇到的是第二种情况,这种有没挽救的余地呢? 要回答这个问题,先得搞清楚sqlite_master是什么。它是一个每个SQLite DB都有的特殊的表, 无论是查看官方文档Database File Format,还是执行SQL语句 SELECT FROM sqlite_master;,都可得知这个系统表保存以下信息: 表名、类型(table/index)、 创建此表/索引的SQL语句,以及表的RootPage。sqlite_master的表名、表结构都是固定的, 由文件格式定义,RootPage 固定为 page 1。 正常情况下,SQLite 引擎打开DB后首次使用,需要先遍历sqlite_master,并将里面保存的SQL语句再解析一遍, 保存在内存中供后续编译SQL语句时使用。假如sqlite_master损坏了无法解析,“Dump恢复”这种走正常SQLite 流程的方法,自然会卡在第一步了。为了让sqlite_master受损的DB也能打开,需要想办法绕过SQLite引擎的逻辑。 由于SQLite引擎初始化逻辑比较复杂,为了避免副作用,没有采用hack的方式复用其逻辑,而是决定仿造一个只可以 读取数据的最小化系统。 虽然仿造最小化系统可以跳过很多正确性校验,但sqlite_master里保存的信息对恢复来说也是十分重要的, 特别是RootPage,因为它是表对应的B-tree结构的根节点所在地,没有了它我们甚至不知道从哪里开始解析对应的表。 sqlite_master信息量比较小,而且只有改变了表结构的时候(例如执行了CREATE TABLE、ALTER TABLE 等语句)才会改变,因此对它进行备份成本是非常低的,一般手机典型只需要几毫秒到数十毫秒即可完成,一致性也容易保证, 只需要执行了上述语句的时候重新备份一次即可。有了备份,我们的逻辑可以在读取DB自带的sqlite_master失败的时候 使用备份的信息来代替。 到此,初始化必须的数据就保证了,可以仿造读取逻辑了。我们常规使用的读取DB的方法(包括dump方式恢复), 都是通过执行SQL语句实现的,这牵涉到SQLite系统最复杂的子系统——SQL执行引擎。我们的恢复任务只需要遍历B-tree所有节点, 读出数据即可完成,不需要复杂的查询逻辑,因此最复杂的SQL引擎可以省略。同时,因为我们的系统是只读的, 写入恢复数据到新 DB 只要直接调用 SQLite 接口即可,因而可以省略同样比较复杂的B-tree平衡、Journal和同步等逻辑。 最后恢复用的最小系统只需要: VFS读取部分的接口(Open/Read/Close),或者直接用stdio的fopen/fread、Posix的open/read也可以 B-tree解析逻辑 Database File Format 详细描述了SQLite文件格式, 参照之实现B-tree解析可读取 SQLite DB。 实现了上面的逻辑,就能读出DB的数据进行恢复了,但还有一个小插曲。我们知道,使用SQLite查询一个表, 每一行的列数都是一致的,这是Schema层面保证的。但是在Schema的下面一层——B-tree层,没有这个保证。 B-tree的每一行(或者说每个entry、每个record)可以有不同的列数,一般来说,SQLite插入一行时, B-tree里面的列数和实际表的列数是一致的。但是当对一个表进行了ALTER TABLE ADD COLUMN操作, 整个表都增加了一列,但已经存在的B-tree行实际上没有做改动,还是维持原来的列数。 当SQLite查询到ALTER TABLE前的行,缺少的列会自动用默认值补全。恢复的时候,也需要做同样的判断和支持, 否则会出现缺列而无法插入到新的DB。 解析B-tree方案上线后,成功率约为78%。这个成功率计算方法为恢复成功的 Page 数除以总 Page 数。 由于是我们自己的系统,可以得知总 Page 数,使用恢复 Page 数比例的计算方法比人数更能反映真实情况。 B-tree解析好处是准备成本较低,不需要经常更新备份,对大部分表比较少的应用备份开销也小到几乎可以忽略, 成功恢复后能还原损坏时最新的数据,不受备份时限影响。 坏处是,和Dump一样,如果损坏到表的中间部分,比如非叶子节点,将导致后续数据无法读出。 落地实践: 剥离封装RepairKit: 从WCDB框架中,剥离修复组件,并且封装其C++的原始API为OC管理类。 备份 master 表的时机: 我们发现 SQLite 里面 B+树 算法的实现是 向下分裂 的,也就是说当一个叶子页满了需要分裂时,原来的叶子页会成为内部节点,然后新申请两个页作为他的叶子页。这就保证了根节点一旦下来,是再也不会变动的。master 表只会在新创建表或者删除一个表时才会发生变化,而CoreData的机制表明每一次数据库的变动都要改动版本标识,那么我通过缓存和查询版本标识的变动来确定何时进行备份,避免频繁备份。 备份文件有效性: 既然 DB 可以损坏,那么这个备份文件也会损坏,怎么办呢?我用了双备份,每一个版本备份两个文件,如果一个备份恢复失败,就会启动另一个备份文件恢复。 介入恢复时机: 当CoreData初始化SQLite前,校验SQLite的Head完整性,如果不完整,进行介入修复。 经过我深入研究证明了这已经是最佳做法。 本篇文章为转载内容。原文链接:https://blog.csdn.net/a66666225/article/details/81637368。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-11-23 18:22:40
127
转载
转载文章
...描述,一边阅读、一边实践、一边理解,定能有意想不到的巨大收获!希望本系列博文能够得到广大园友的高度推荐。 15 Advanced ASP.NET Identity 15 ASP.NET Identity高级技术 In this chapter, I finish my description of ASP.NET Identity by showing you some of the advanced features it offers. I demonstrate how you can extend the database schema by defining custom properties on the user class and how to use database migrations to apply those properties without deleting the data in the ASP.NET Identity database. I also explain how ASP.NET Identity supports the concept of claims and demonstrates how they can be used to flexibly authorize access to action methods. I finish the chapter—and the book—by showing you how ASP.NET Identity makes it easy to authenticate users through third parties. I demonstrate authentication with Google accounts, but ASP.NET Identity has built-in support for Microsoft, Facebook, and Twitter accounts as well. Table 15-1 summarizes this chapter. 本章将完成对ASP.NET Identity的描述,向你展示它所提供的一些高级特性。我将演示,你可以扩展ASP.NET Identity的数据库架构,其办法是在用户类上定义一些自定义属性。也会演示如何使用数据库迁移,这样可以运用自定义属性,而不必删除ASP.NET Identity数据库中的数据。还会解释ASP.NET Identity如何支持声明(Claims)概念,并演示如何将它们灵活地用来对动作方法进行授权访问。最后向你展示ASP.NET Identity很容易通过第三方部件来认证用户,以此结束本章以及本书。将要演示的是使用Google账号认证,但ASP.NET Identity对于Microsoft、Facebook以及Twitter账号,都有内建的支持。表15-1是本章概要。 Table 15-1. Chapter Summary 表15-1. 本章概要 Problem 问题 Solution 解决方案 Listing 清单号 Store additional information about users. 存储用户的附加信息 Define custom user properties. 定义自定义用户属性 1–3, 8–11 Update the database schema without deleting user data. 更新数据库架构而不删除用户数据 Perform a database migration. 执行数据库迁移 4–7 Perform fine-grained authorization. 执行细粒度授权 Use claims. 使用声明(Claims) 12–14 Add claims about a user. 添加用户的声明(Claims) Use the ClaimsIdentity.AddClaims method. 使用ClaimsIdentity.AddClaims方法 15–19 Authorize access based on claim values. 基于声明(Claims)值授权访问 Create a custom authorization filter attribute. 创建一个自定义的授权过滤器注解属性 20–21 Authenticate through a third party. 通过第三方认证 Install the NuGet package for the authentication provider, redirect requests to that provider, and specify a callback URL that creates the user account. 安装认证提供器的NuGet包,将请求重定向到该提供器,并指定一个创建用户账号的回调URL。 22–25 15.1 Preparing the Example Project 15.1 准备示例项目 In this chapter, I am going to continue working on the Users project I created in Chapter 13 and enhanced in Chapter 14. No changes to the application are required, but start the application and make sure that there are users in the database. Figure 15-1 shows the state of my database, which contains the users Admin, Alice, Bob, and Joe from the previous chapter. To check the users, start the application and request the /Admin/Index URL and authenticate as the Admin user. 本章打算继续使用第13章创建并在第14章增强的Users项目。对应用程序无需做什么改变,但需要启动应用程序,并确保数据库中有一些用户。图15-1显示了数据库的状态,它含有上一章的用户Admin、Alice、Bob以及Joe。为了检查用户,请启动应用程序,请求/Admin/Index URL,并以Admin用户进行认证。 Figure 15-1. The initial users in the Identity database 图15-1. Identity数据库中的最初用户 I also need some roles for this chapter. I used the RoleAdmin controller to create roles called Users and Employees and assigned the users to those roles, as described in Table 15-2. 本章还需要一些角色。我用RoleAdmin控制器创建了角色Users和Employees,并为这些角色指定了一些用户,如表15-2所示。 Table 15-2. The Types of Web Forms Code Nuggets 表15-2. 角色及成员(作者将此表的标题写错了——译者注) Role 角色 Members 成员 Users Alice, Joe Employees Alice, Bob Figure 15-2 shows the required role configuration displayed by the RoleAdmin controller. 图15-2显示了由RoleAdmin控制器所显示出来的必要的角色配置。 Figure 15-2. Configuring the roles required for this chapter 图15-2. 配置本章所需的角色 15.2 Adding Custom User Properties 15.2 添加自定义用户属性 When I created the AppUser class to represent users in Chapter 13, I noted that the base class defined a basic set of properties to describe the user, such as e-mail address and telephone number. Most applications need to store more information about users, including persistent application preferences and details such as addresses—in short, any data that is useful to running the application and that should last between sessions. In ASP.NET Membership, this was handled through the user profile system, but ASP.NET Identity takes a different approach. 我在第13章创建AppUser类来表示用户时曾做过说明,基类定义了一组描述用户的基本属性,如E-mail地址、电话号码等。大多数应用程序还需要存储用户的更多信息,包括持久化应用程序爱好以及地址等细节——简言之,需要存储对运行应用程序有用并且在各次会话之间应当保持的任何数据。在ASP.NET Membership中,这是通过用户资料(User Profile)系统来处理的,但ASP.NET Identity采取了一种不同的办法。 Because the ASP.NET Identity system uses Entity Framework to store its data by default, defining additional user information is just a matter of adding properties to the user class and letting the Code First feature create the database schema required to store them. Table 15-3 puts custom user properties in context. 因为ASP.NET Identity默认是使用Entity Framework来存储其数据的,定义附加的用户信息只不过是给用户类添加属性的事情,然后让Code First特性去创建需要存储它们的数据库架构即可。表15-3描述了自定义用户属性的情形。 Table 15-3. Putting Cusotm User Properties in Context 表15-3. 自定义用户属性的情形 Question 问题 Answer 回答 What is it? 什么是自定义用户属性? Custom user properties allow you to store additional information about your users, including their preferences and settings. 自定义用户属性让你能够存储附加的用户信息,包括他们的爱好和设置。 Why should I care? 为何要关心它? A persistent store of settings means that the user doesn’t have to provide the same information each time they log in to the application. 设置的持久化存储意味着,用户不必每次登录到应用程序时都提供同样的信息。 How is it used by the MVC framework? 在MVC框架中如何使用它? This feature isn’t used directly by the MVC framework, but it is available for use in action methods. 此特性不是由MVC框架直接使用的,但它在动作方法中使用是有效的。 15.2.1 Defining Custom Properties 15.2.1 定义自定义属性 Listing 15-1 shows how I added a simple property to the AppUser class to represent the city in which the user lives. 清单15-1演示了如何给AppUser类添加一个简单的属性,用以表示用户生活的城市。 Listing 15-1. Adding a Property in the AppUser.cs File 清单15-1. 在AppUser.cs文件中添加属性 using System;using Microsoft.AspNet.Identity.EntityFramework;namespace Users.Models { public enum Cities {LONDON, PARIS, CHICAGO}public class AppUser : IdentityUser {public Cities City { get; set; } }} I have defined an enumeration called Cities that defines values for some large cities and added a property called City to the AppUser class. To allow the user to view and edit their City property, I added actions to the Home controller, as shown in Listing 15-2. 这里定义了一个枚举,名称为Cities,它定义了一些大城市的值,另外给AppUser类添加了一个名称为City的属性。为了让用户能够查看和编辑City属性,给Home控制器添加了几个动作方法,如清单15-2所示。 Listing 15-2. Adding Support for Custom User Properties in the HomeController.cs File 清单15-2. 在HomeController.cs文件中添加对自定义属性的支持 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models;namespace Users.Controllers {public class HomeController : Controller {[Authorize]public ActionResult Index() {return View(GetData("Index"));}[Authorize(Roles = "Users")]public ActionResult OtherAction() {return View("Index", GetData("OtherAction"));}private Dictionary<string, object> GetData(string actionName) {Dictionary<string, object> dict= new Dictionary<string, object>();dict.Add("Action", actionName);dict.Add("User", HttpContext.User.Identity.Name);dict.Add("Authenticated", HttpContext.User.Identity.IsAuthenticated);dict.Add("Auth Type", HttpContext.User.Identity.AuthenticationType);dict.Add("In Users Role", HttpContext.User.IsInRole("Users"));return dict;} [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;await UserManager.UpdateAsync(user);return View(user);}private AppUser CurrentUser {get {return UserManager.FindByName(HttpContext.User.Identity.Name);} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } I added a CurrentUser property that uses the AppUserManager class to retrieve an AppUser instance to represent the current user. I pass the AppUser object as the view model object in the GET version of the UserProps action method, and the POST method uses it to update the value of the new City property. Listing 15-3 shows the UserProps.cshtml view, which displays the City property value and contains a form to change it. 我添加了一个CurrentUser属性,它使用AppUserManager类接收了表示当前用户的AppUser实例。在GET版本的UserProps动作方法中,传递了这个AppUser对象作为视图模型。而在POST版的方法中用它更新了City属性的值。清单15-3显示了UserProps.cshtml视图,它显示了City属性的值,并包含一个修改它的表单。 Listing 15-3. The Contents of the UserProps.cshtml File in the Views/Home Folder 清单15-3. Views/Home文件夹中UserProps.cshtml文件的内容 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";}<div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr></table></div> @using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Caution Don’t start the application when you have created the view. In the sections that follow, I demonstrate how to preserve the contents of the database, and if you start the application now, the ASP.NET Identity users will be deleted. 警告:创建了视图之后不要启动应用程序。在以下小节中,将演示如何保留数据库的内容,如果现在启动应用程序,将会删除ASP.NET Identity的用户。 15.2.2 Preparing for Database Migration 15.2.2 准备数据库迁移 The default behavior for the Entity Framework Code First feature is to drop the tables in the database and re-create them whenever classes that drive the schema have changed. You saw this in Chapter 14 when I added support for roles: When the application was started, the database was reset, and the user accounts were lost. Entity Framework Code First特性的默认行为是,一旦修改了派生数据库架构的类,便会删除数据库中的数据表,并重新创建它们。在第14章可以看到这种情况,在我添加角色支持时:当重启应用程序后,数据库被重置,用户账号也丢失。 Don’t start the application yet, but if you were to do so, you would see a similar effect. Deleting data during development is usually not a problem, but doing so in a production setting is usually disastrous because it deletes all of the real user accounts and causes a panic while the backups are restored. In this section, I am going to demonstrate how to use the database migration feature, which updates a Code First schema in a less brutal manner and preserves the existing data it contains. 不要启动应用程序,但如果你这么做了,会看到类似的效果。在开发期间删除数据没什么问题,但如果在产品设置中这么做了,通常是灾难性的,因为它会删除所有真实的用户账号,而备份恢复是很痛苦的事。在本小节中,我打算演示如何使用数据库迁移特性,它能以比较温和的方式更新Code First的架构,并保留架构中的已有数据。 The first step is to issue the following command in the Visual Studio Package Manager Console: 第一个步骤是在Visual Studio的“Package Manager Console(包管理器控制台)”中发布以下命令: Enable-Migrations –EnableAutomaticMigrations This enables the database migration support and creates a Migrations folder in the Solution Explorer that contains a Configuration.cs class file, the contents of which are shown in Listing 15-4. 它启用了数据库的迁移支持,并在“Solution Explorer(解决方案资源管理器)”创建一个Migrations文件夹,其中含有一个Configuration.cs类文件,内容如清单15-4所示。 Listing 15-4. The Contents of the Configuration.cs File 清单15-4. Configuration.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity;using System.Data.Entity.Migrations;using System.Linq;internal sealed class Configuration: DbMigrationsConfiguration<Users.Infrastructure.AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(Users.Infrastructure.AppIdentityDbContext context) {// This method will be called after migrating to the latest version.// 此方法将在迁移到最新版本时调用// You can use the DbSet<T>.AddOrUpdate() helper extension method// to avoid creating duplicate seed data. E.g.// 例如,你可以使用DbSet<T>.AddOrUpdate()辅助器方法来避免创建重复的种子数据//// context.People.AddOrUpdate(// p => p.FullName,// new Person { FullName = "Andrew Peters" },// new Person { FullName = "Brice Lambson" },// new Person { FullName = "Rowan Miller" }// );//} }} Tip You might be wondering why you are entering a database migration command into the console used to manage NuGet packages. The answer is that the Package Manager Console is really PowerShell, which is a general-purpose tool that is mislabeled by Visual Studio. You can use the console to issue a wide range of helpful commands. See http://go.microsoft.com/fwlink/?LinkID=108518 for details. 提示:你可能会觉得奇怪,为什么要在管理NuGet包的控制台中输入数据库迁移的命令?答案是“Package Manager Console(包管理控制台)”是真正的PowerShell,这是Visual studio冒用的一个通用工具。你可以使用此控制台发送大量的有用命令,详见http://go.microsoft.com/fwlink/?LinkID=108518。 The class will be used to migrate existing content in the database to the new schema, and the Seed method will be called to provide an opportunity to update the existing database records. In Listing 15-5, you can see how I have used the Seed method to set a default value for the new City property I added to the AppUser class. (I have also updated the class file to reflect my usual coding style.) 这个类将用于把数据库中的现有内容迁移到新的数据库架构,Seed方法的调用为更新现有数据库记录提供了机会。在清单15-5中可以看到,我如何用Seed方法为新的City属性设置默认值,City是添加到AppUser类中自定义属性。(为了体现我一贯的编码风格,我对这个类文件也进行了更新。) Listing 15-5. Managing Existing Content in the Configuration.cs File 清单15-5. 在Configuration.cs文件中管理已有内容 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models;namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);}foreach (AppUser dbUser in userMgr.Users) {dbUser.City = Cities.PARIS;}context.SaveChanges();} }} You will notice that much of the code that I added to the Seed method is taken from the IdentityDbInit class, which I used to seed the database with an administration user in Chapter 14. This is because the new Configuration class added to support database migrations will replace the seeding function of the IdentityDbInit class, which I’ll update shortly. Aside from ensuring that there is an admin user, the statements in the Seed method that are important are the ones that set the initial value for the City property I added to the AppUser class, as follows: 你可能会注意到,添加到Seed方法中的许多代码取自于IdentityDbInit类,在第14章中我用这个类将管理用户植入了数据库。这是因为这个新添加的、用以支持数据库迁移的Configuration类,将代替IdentityDbInit类的种植功能,我很快便会更新这个类。除了要确保有admin用户之外,在Seed方法中的重要语句是那些为AppUser类的City属性设置初值的语句,如下所示: ...foreach (AppUser dbUser in userMgr.Users) { dbUser.City = Cities.PARIS;}context.SaveChanges();... You don’t have to set a default value for new properties—I just wanted to demonstrate that the Seed method in the Configuration class can be used to update the existing user records in the database. 你不一定要为新属性设置默认值——这里只是想演示Configuration类中的Seed方法,可以用它更新数据库中的已有用户记录。 Caution Be careful when setting values for properties in the Seed method for real projects because the values will be applied every time you change the schema, overriding any values that the user has set since the last schema update was performed. I set the value of the City property just to demonstrate that it can be done. 警告:在用于真实项目的Seed方法中为属性设置值时要小心,因为你每一次修改架构时,都会运用这些值,这会将自执行上一次架构更新之后,用户设置的任何数据覆盖掉。这里设置City属性的值只是为了演示它能够这么做。 Changing the Database Context Class 修改数据库上下文类 The reason that I added the seeding code to the Configuration class is that I need to change the IdentityDbInit class. At present, the IdentityDbInit class is derived from the descriptively named DropCreateDatabaseIfModelChanges<AppIdentityDbContext> class, which, as you might imagine, drops the entire database when the Code First classes change. Listing 15-6 shows the changes I made to the IdentityDbInit class to prevent it from affecting the database. 在Configuration类中添加种植代码的原因是我需要修改IdentityDbInit类。此时,IdentityDbInit类派生于描述性命名的DropCreateDatabaseIfModelChanges<AppIdentityDbContext> 类,和你相像的一样,它会在Code First类改变时删除整个数据库。清单15-6显示了我对IdentityDbInit类所做的修改,以防止它影响数据库。 Listing 15-6. Preventing Database Schema Changes in the AppIdentityDbContext.cs File 清单15-6. 在AppIdentityDbContext.cs文件是阻止数据库架构变化 using System.Data.Entity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Models;using Microsoft.AspNet.Identity; namespace Users.Infrastructure {public class AppIdentityDbContext : IdentityDbContext<AppUser> {public AppIdentityDbContext() : base("IdentityDb") { }static AppIdentityDbContext() {Database.SetInitializer<AppIdentityDbContext>(new IdentityDbInit());}public static AppIdentityDbContext Create() {return new AppIdentityDbContext();} } public class IdentityDbInit : NullDatabaseInitializer<AppIdentityDbContext> {} } I have removed the methods defined by the class and changed its base to NullDatabaseInitializer<AppIdentityDbContext> , which prevents the schema from being altered. 我删除了这个类中所定义的方法,并将它的基类改为NullDatabaseInitializer<AppIdentityDbContext> ,它可以防止架构修改。 15.2.3 Performing the Migration 15.2.3 执行迁移 All that remains is to generate and apply the migration. First, run the following command in the Package Manager Console: 剩下的事情只是生成并运用迁移了。首先,在“Package Manager Console(包管理器控制台)”中执行以下命令: Add-Migration CityProperty This creates a new migration called CityProperty (I like my migration names to reflect the changes I made). A class new file will be added to the Migrations folder, and its name reflects the time at which the command was run and the name of the migration. My file is called 201402262244036_CityProperty.cs, for example. The contents of this file contain the details of how Entity Framework will change the database during the migration, as shown in Listing 15-7. 这创建了一个名称为CityProperty的新迁移(我比较喜欢让迁移的名称反映出我所做的修改)。这会在文件夹中添加一个新的类文件,而且其命名会反映出该命令执行的时间以及迁移名称,例如,我的这个文件名称为201402262244036_CityProperty.cs。该文件的内容含有迁移期间Entity Framework修改数据库的细节,如清单15-7所示。 Listing 15-7. The Contents of the 201402262244036_CityProperty.cs File 清单15-7. 201402262244036_CityProperty.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity.Migrations; public partial class Init : DbMigration {public override void Up() {AddColumn("dbo.AspNetUsers", "City", c => c.Int(nullable: false));}public override void Down() {DropColumn("dbo.AspNetUsers", "City");} }} The Up method describes the changes that have to be made to the schema when the database is upgraded, which in this case means adding a City column to the AspNetUsers table, which is the one that is used to store user records in the ASP.NET Identity database. Up方法描述了在数据库升级时,需要对架构所做的修改,在这个例子中,意味着要在AspNetUsers数据表中添加City数据列,该数据表是ASP.NET Identity数据库用来存储用户记录的。 The final step is to perform the migration. Without starting the application, run the following command in the Package Manager Console: 最后一步是执行迁移。无需启动应用程序,只需在“Package Manager Console(包管理器控制台)”中运行以下命令即可: Update-Database –TargetMigration CityProperty The database schema will be modified, and the code in the Configuration.Seed method will be executed. The existing user accounts will have been preserved and enhanced with a City property (which I set to Paris in the Seed method). 这会修改数据库架构,并执行Configuration.Seed方法中的代码。已有用户账号会被保留,且增强了City属性(我在Seed方法中已将其设置为“Paris”)。 15.2.4 Testing the Migration 15.2.4 测试迁移 To test the effect of the migration, start the application, navigate to the /Home/UserProps URL, and authenticate as one of the Identity users (for example, as Alice with the password MySecret). Once authenticated, you will see the current value of the City property for the user and have the opportunity to change it, as shown in Figure 15-3. 为了测试迁移的效果,启动应用程序,导航到/Home/UserProps URL,并以Identity中的用户(例如Alice,口令MySecret)进行认证。一旦已被认证,便会看到该用户City属性的当前值,并可以对其进行修改,如图15-3所示。 Figure 15-3. Displaying and changing a custom user property 图15-3. 显示和个性自定义用户属性 15.2.5 Defining an Additional Property 15.2.5 定义附加属性 Now that database migrations are set up, I am going to define a further property just to demonstrate how subsequent changes are handled and to show a more useful (and less dangerous) example of using the Configuration.Seed method. Listing 15-8 shows how I added a Country property to the AppUser class. 现在,已经建立了数据库迁移,我打算再定义一个属性,这恰恰演示了如何处理持续不断的修改,也为了演示Configuration.Seed方法更有用(至少无害)的示例。清单15-8显示了我在AppUser类上添加了一个Country属性。 Listing 15-8. Adding Another Property in the AppUserModels.cs File 清单15-8. 在AppUserModels.cs文件中添加另一个属性 using System;using Microsoft.AspNet.Identity.EntityFramework; namespace Users.Models {public enum Cities {LONDON, PARIS, CHICAGO} public enum Countries {NONE, UK, FRANCE, USA}public class AppUser : IdentityUser {public Cities City { get; set; }public Countries Country { get; set; }public void SetCountryFromCity(Cities city) {switch (city) {case Cities.LONDON:Country = Countries.UK;break;case Cities.PARIS:Country = Countries.FRANCE;break;case Cities.CHICAGO:Country = Countries.USA;break;default:Country = Countries.NONE;break;} }} } I have added an enumeration to define the country names and a helper method that selects a country value based on the City property. Listing 15-9 shows the change I made to the Configuration class so that the Seed method sets the Country property based on the City, but only if the value of Country is NONE (which it will be for all users when the database is migrated because the Entity Framework sets enumeration columns to the first value). 我已经添加了一个枚举,它定义了国家名称。还添加了一个辅助器方法,它可以根据City属性选择一个国家。清单15-9显示了对Configuration类所做的修改,以使Seed方法根据City设置Country属性,但只当Country为NONE时才进行设置(在迁移数据库时,所有用户都是NONE,因为Entity Framework会将枚举列设置为枚举的第一个值)。 Listing 15-9. Modifying the Database Seed in the Configuration.cs File 清单15-9. 在Configuration.cs文件中修改数据库种子 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models; namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);} foreach (AppUser dbUser in userMgr.Users) {if (dbUser.Country == Countries.NONE) {dbUser.SetCountryFromCity(dbUser.City);} }context.SaveChanges();} }} This kind of seeding is more useful in a real project because it will set a value for the Country property only if one has not already been set—subsequent migrations won’t be affected, and user selections won’t be lost. 这种种植在实际项目中会更有用,因为它只会在Country属性未设置时,才会设置Country属性的值——后继的迁移不会受到影响,因此不会失去用户的选择。 1. Adding Application Support 1. 添加应用程序支持 There is no point defining additional user properties if they are not available in the application, so Listing 15-10 shows the change I made to the Views/Home/UserProps.cshtml file to display the value of the Country property. 应用程序中如果没有定义附加属性的地方,则附加属性就无法使用了,因此,清单15-10显示了我对Views/Home/UserProps.cshtml文件的修改,以显示Country属性的值。 Listing 15-10. Displaying an Additional Property in the UserProps.cshtml File 清单15-10. 在UserProps.cshtml文件中显示附加属性 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";} <div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr> <tr><th>Country</th><td>@Model.Country</td></tr></table></div>@using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Listing 15-11 shows the corresponding change I made to the Home controller to update the Country property when the City value changes. 为了在City值变化时能够更新Country属性,清单15-11显示了我对Home控制器所做的相应修改。 Listing 15-11. Setting Custom Properties in the HomeController.cs File 清单15-11. 在HomeController.cs文件中设置自定义属性 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models; namespace Users.Controllers {public class HomeController : Controller {// ...other action methods omitted for brevity...// ...出于简化,这里忽略了其他动作方法... [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;user.SetCountryFromCity(city);await UserManager.UpdateAsync(user);return View(user);}// ...properties omitted for brevity...// ...出于简化,这里忽略了一些属性...} } 2. Performing the Migration 2. 准备迁移 All that remains is to create and apply a new migration. Enter the following command into the Package Manager Console: 剩下的事情就是创建和运用新的迁移了。在“Package Manager Console(包管理器控制台)”中输入以下命令: Add-Migration CountryProperty This will generate another file in the Migrations folder that contains the instruction to add the Country column. To apply the migration, execute the following command: 这将在Migrations文件夹中生成另一个文件,它含有添加Country数据表列的指令。为了运用迁移,可执行以下命令: Update-Database –TargetMigration CountryProperty The migration will be performed, and the value of the Country property will be set based on the value of the existing City property for each user. You can check the new user property by starting the application and authenticating and navigating to the /Home/UserProps URL, as shown in Figure 15-4. 这将执行迁移,Country属性的值将根据每个用户当前的City属性进行设置。通过启动应用程序,认证并导航到/Home/UserProps URL,便可以查看新的用户属性,如图15-4所示。 Figure 15-4. Creating an additional user property 图15-4. 创建附加用户属性 Tip Although I am focused on the process of upgrading the database, you can also migrate back to a previous version by specifying an earlier migration. Use the –Force argument make changes that cause data loss, such as removing a column. 提示:虽然我们关注了升级数据库的过程,但你也可以回退到以前的版本,只需指定一个早期的迁移即可。使用-Force参数进行修改,会引起数据丢失,例如删除数据表列。 15.3 Working with Claims 15.3 使用声明(Claims) In older user-management systems, such as ASP.NET Membership, the application was assumed to be the authoritative source of all information about the user, essentially treating the application as a closed world and trusting the data that is contained within it. 在旧的用户管理系统中,例如ASP.NET Membership,应用程序被假设成是用户所有信息的权威来源,本质上将应用程序视为是一个封闭的世界,并且只信任其中所包含的数据。 This is such an ingrained approach to software development that it can be hard to recognize that’s what is happening, but you saw an example of the closed-world technique in Chapter 14 when I authenticated users against the credentials stored in the database and granted access based on the roles associated with those credentials. I did the same thing again in this chapter when I added properties to the user class. Every piece of information that I needed to manage user authentication and authorization came from within my application—and that is a perfectly satisfactory approach for many web applications, which is why I demonstrated these techniques in such depth. 这是软件开发的一种根深蒂固的方法,使人很难认识到这到底意味着什么,第14章你已看到了这种封闭世界技术的例子,根据存储在数据库中的凭据来认证用户,并根据与凭据关联在一起的角色来授权访问。本章前述在用户类上添加属性,也做了同样的事情。我管理用户认证与授权所需的每一个数据片段都来自于我的应用程序——而且这是许多Web应用程序都相当满意的一种方法,这也是我如此深入地演示这些技术的原因。 ASP.NET Identity also supports an alternative approach for dealing with users, which works well when the MVC framework application isn’t the sole source of information about users and which can be used to authorize users in more flexible and fluid ways than traditional roles allow. ASP.NET Identity还支持另一种处理用户的办法,当MVC框架的应用程序不是有关用户的唯一信息源时,这种办法会工作得很好,而且能够比传统的角色授权更为灵活且流畅的方式进行授权。 This alternative approach uses claims, and in this section I’ll describe how ASP.NET Identity supports claims-based authorization. Table 15-4 puts claims in context. 这种可选的办法使用了“Claims(声明)”,因此在本小节中,我将描述ASP.NET Identity如何支持“Claims-Based Authorization(基于声明的授权)”。表15-4描述了声明(Claims)的情形。 提示:“Claim”在英文字典中不完全是“声明”的意思,根据本文的描述,感觉把它说成“声明”也不一定合适,所以在之后的译文中基本都写成中英文并用的形式,即“声明(Claims)”。根据表15-4中的声明(Claims)的定义:声明(Claims)是关于用户的一些信息片段。一个用户的信息片段当然有很多,每一个信息片段就是一项声明(Claim),用户的所有信息片段合起来就是该用户的声明(Claims)。请读者注意该单词的单复数形式——译者注 Table 15-4. Putting Claims in Context 表15-4. 声明(Claims)的情形 Question 问题 Answer 答案 What is it? 什么是声明(Claims)? Claims are pieces of information about users that you can use to make authorization decisions. Claims can be obtained from external systems as well as from the local Identity database. 声明(Claims)是关于用户的一些信息片段,可以用它们做出授权决定。声明(Claims)可以从外部系统获取,也可以从本地的Identity数据库获取。 Why should I care? 为何要关心它? Claims can be used to flexibly authorize access to action methods. Unlike conventional roles, claims allow access to be driven by the information that describes the user. 声明(Claims)可以用来对动作方法进行灵活的授权访问。与传统的角色不同,声明(Claims)让访问能够由描述用户的信息进行驱动。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework, but it is integrated into the standard authorization features, such as the Authorize attribute. 这不是直接由MVC框架使用的特性,但它集成到了标准的授权特性之中,例如Authorize注解属性。 Tip you don’t have to use claims in your applications, and as Chapter 14 showed, ASP.NET Identity is perfectly happy providing an application with the authentication and authorization services without any need to understand claims at all. 提示:你在应用程序中不一定要使用声明(Claims),正如第14章所展示的那样,ASP.NET Identity能够为应用程序提供充分的认证与授权服务,而根本不需要理解声明(Claims)。 15.3.1 Understanding Claims 15.3.1 理解声明(Claims) A claim is a piece of information about the user, along with some information about where the information came from. The easiest way to unpack claims is through some practical demonstrations, without which any discussion becomes too abstract to be truly useful. To get started, I added a Claims controller to the example project, the definition of which you can see in Listing 15-12. 一项声明(Claim)是关于用户的一个信息片段(请注意这个英文单词的单复数形式——译者注),并伴有该片段出自何处的某种信息。揭开声明(Claims)含义最容易的方式是做一些实际演示,任何讨论都会过于抽象根本没有真正的用处。为此,我在示例项目中添加了一个Claims控制器,其定义如清单15-12所示。 Listing 15-12. The Contents of the ClaimsController.cs File 清单15-12. ClaimsController.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} }} } Tip You may feel a little lost as I define the code for this example. Don’t worry about the details for the moment—just stick with it until you see the output from the action method and view that I define. More than anything else, that will help put claims into perspective. 提示:你或许会对我为此例定义的代码感到有点失望。此刻对此细节不必着急——只要稍事忍耐,当看到该动作方法和视图的输出便会明白。尤为重要的是,这有助于洞察声明(Claims)。 You can get the claims associated with a user in different ways. One approach is to use the Claims property defined by the user class, but in this example, I have used the HttpContext.User.Identity property to demonstrate the way that ASP.NET Identity is integrated with the rest of the ASP.NET platform. As I explained in Chapter 13, the HttpContext.User.Identity property returns an implementation of the IIdentity interface, which is a ClaimsIdentity object when working using ASP.NET Identity. The ClaimsIdentity class is defined in the System.Security.Claims namespace, and Table 15-5 shows the members it defines that are relevant to this chapter. 可以通过不同的方式获得与用户相关联的声明(Claims)。方法之一就是使用由用户类定义的Claims属性,但在这个例子中,我使用了HttpContext.User.Identity属性,目的是演示ASP.NET Identity与ASP.NET平台集成的方式(请注意这句话所表示的含义:用户类的Claims属性属于ASP.NET Identity,而HttpContext.User.Identity属性则属于ASP.NET平台。由此可见,ASP.NET Identity已经融合到了ASP.NET平台之中——译者注)。正如第13章所解释的那样,HttpContext.User.Identity属性返回IIdentity的接口实现,当使用ASP.NET Identity时,该实现是一个ClaimsIdentity对象。ClaimsIdentity类是在System.Security.Claims命名空间中定义的,表15-5显示了它所定义的与本章有关的成员。 Table 15-5. The Members Defined by the ClaimsIdentity Class 表15-5. ClaimsIdentity类所定义的成员 Name 名称 Description 描述 Claims Returns an enumeration of Claim objects representing the claims for the user. 返回表示用户声明(Claims)的Claim对象枚举 AddClaim(claim) Adds a claim to the user identity. 给用户添加一个声明(Claim) AddClaims(claims) Adds an enumeration of Claim objects to the user identity. 给用户添加Claim对象的枚举。 HasClaim(predicate) Returns true if the user identity contains a claim that matches the specified predicate. See the “Applying Claims” section for an example predicate. 如果用户含有与指定谓词匹配的声明(Claim)时,返回true。参见“运用声明(Claims)”中的示例谓词 RemoveClaim(claim) Removes a claim from the user identity. 删除用户的声明(Claim)。 Other members are available, but the ones in the table are those that are used most often in web applications, for reason that will become obvious as I demonstrate how claims fit into the wider ASP.NET platform. 还有一些可用的其它成员,但表中的这些是在Web应用程序中最常用的,随着我演示如何将声明(Claims)融入更宽泛的ASP.NET平台,它们为什么最常用就很显然了。 In Listing 15-12, I cast the IIdentity implementation to the ClaimsIdentity type and pass the enumeration of Claim objects returned by the ClaimsIdentity.Claims property to the View method. A Claim object represents a single piece of data about the user, and the Claim class defines the properties shown in Table 15-6. 在清单15-12中,我将IIdentity实现转换成了ClaimsIdentity类型,并且给View方法传递了ClaimsIdentity.Claims属性所返回的Claim对象的枚举。Claim对象所示表示的是关于用户的一个单一的数据片段,Claim类定义的属性如表15-6所示。 Table 15-6. The Properties Defined by the Claim Class 表15-6. Claim类定义的属性 Name 名称 Description 描述 Issuer Returns the name of the system that provided the claim 返回提供声明(Claim)的系统名称 Subject Returns the ClaimsIdentity object for the user who the claim refers to 返回声明(Claim)所指用户的ClaimsIdentity对象 Type Returns the type of information that the claim represents 返回声明(Claim)所表示的信息类型 Value Returns the piece of information that the claim represents 返回声明(Claim)所表示的信息片段 Listing 15-13 shows the contents of the Index.cshtml file that I created in the Views/Claims folder and that is rendered by the Index action of the Claims controller. The view adds a row to a table for each claim about the user. 清单15-13显示了我在Views/Claims文件夹中创建的Index.cshtml文件的内容,它由Claims控制器中的Index动作方法进行渲染。该视图为用户的每项声明(Claim)添加了一个表格行。 Listing 15-13. The Contents of the Index.cshtml File in the Views/Claims Folder 清单15-13. Views/Claims文件夹中Index.cshtml文件的内容 @using System.Security.Claims@using Users.Infrastructure@model IEnumerable<Claim>@{ ViewBag.Title = "Claims"; }<div class="panel panel-primary"><div class="panel-heading">Claims</div><table class="table table-striped"><tr><th>Subject</th><th>Issuer</th><th>Type</th><th>Value</th></tr>@foreach (Claim claim in Model.OrderBy(x => x.Type)) {<tr><td>@claim.Subject.Name</td><td>@claim.Issuer</td><td>@Html.ClaimType(claim.Type)</td><td>@claim.Value</td></tr>}</table></div> The value of the Claim.Type property is a URI for a Microsoft schema, which isn’t especially useful. The popular schemas are used as the values for fields in the System.Security.Claims.ClaimTypes class, so to make the output from the Index.cshtml view easier to read, I added an HTML helper to the IdentityHelpers.cs file, as shown in Listing 15-14. It is this helper that I use in the Index.cshtml file to format the value of the Claim.Type property. Claim.Type属性的值是一个微软模式(Microsoft Schema)的URI(统一资源标识符),这是特别有用的。System.Security.Claims.ClaimTypes类中字段的值使用的是流行模式(Popular Schema),因此为了使Index.cshtml视图的输出更易于阅读,我在IdentityHelpers.cs文件中添加了一个HTML辅助器,如清单15-14所示。Index.cshtml文件正是使用这个辅助器格式化了Claim.Type属性的值。 Listing 15-14. Adding a Helper to the IdentityHelpers.cs File 清单15-14. 在IdentityHelpers.cs文件中添加辅助器 using System.Web;using System.Web.Mvc;using Microsoft.AspNet.Identity.Owin;using System;using System.Linq;using System.Reflection;using System.Security.Claims;namespace Users.Infrastructure {public static class IdentityHelpers {public static MvcHtmlString GetUserName(this HtmlHelper html, string id) {AppUserManager mgr= HttpContext.Current.GetOwinContext().GetUserManager<AppUserManager>();return new MvcHtmlString(mgr.FindByIdAsync(id).Result.UserName);} public static MvcHtmlString ClaimType(this HtmlHelper html, string claimType) {FieldInfo[] fields = typeof(ClaimTypes).GetFields();foreach (FieldInfo field in fields) {if (field.GetValue(null).ToString() == claimType) {return new MvcHtmlString(field.Name);} }return new MvcHtmlString(string.Format("{0}",claimType.Split('/', '.').Last()));} }} Note The helper method isn’t at all efficient because it reflects on the fields of the ClaimType class for each claim that is displayed, but it is sufficient for my purposes in this chapter. You won’t often need to display the claim type in real applications. 注:该辅助器并非十分有效,因为它只是针对每个要显示的声明(Claim)映射出ClaimType类的字段,但对我要的目的已经足够了。在实际项目中不会经常需要显示声明(Claim)的类型。 To see why I have created a controller that uses claims without really explaining what they are, start the application, authenticate as the user Alice (with the password MySecret), and request the /Claims/Index URL. Figure 15-5 shows the content that is generated. 为了弄明白我为何要先创建一个使用声明(Claims)的控制器,而没有真正解释声明(Claims)是什么的原因,可以启动应用程序,以用户Alice进行认证(其口令是MySecret),并请求/Claims/Index URL。图15-5显示了生成的内容。 Figure 15-5. The output from the Index action of the Claims controller 图15-5. Claims控制器中Index动作的输出 It can be hard to make out the detail in the figure, so I have reproduced the content in Table 15-7. 这可能还难以认识到此图的细节,为此我在表15-7中重列了其内容。 Table 15-7. The Data Shown in Figure 15-5 表15-7. 图15-5中显示的数据 Subject(科目) Issuer(发行者) Type(类型) Value(值) Alice LOCAL AUTHORITY SecurityStamp Unique ID Alice LOCAL AUTHORITY IdentityProvider ASP.NET Identity Alice LOCAL AUTHORITY Role Employees Alice LOCAL AUTHORITY Role Users Alice LOCAL AUTHORITY Name Alice Alice LOCAL AUTHORITY NameIdentifier Alice’s user ID The table shows the most important aspect of claims, which is that I have already been using them when I implemented the traditional authentication and authorization features in Chapter 14. You can see that some of the claims relate to user identity (the Name claim is Alice, and the NameIdentifier claim is Alice’s unique user ID in my ASP.NET Identity database). 此表展示了声明(Claims)最重要的方面,这些是我在第14章中实现传统的认证和授权特性时,一直在使用的信息。可以看出,有些声明(Claims)与用户标识有关(Name声明是Alice,NameIdentifier声明是Alice在ASP.NET Identity数据库中的唯一用户ID号)。 Other claims show membership of roles—there are two Role claims in the table, reflecting the fact that Alice is assigned to both the Users and Employees roles. There is also a claim about how Alice has been authenticated: The IdentityProvider is set to ASP.NET Identity. 其他声明(Claims)显示了角色成员——表中有两个Role声明(Claim),体现出Alice被赋予了Users和Employees两个角色这一事实。还有一个是Alice已被认证的声明(Claim):IdentityProvider被设置到了ASP.NET Identity。 The difference when this information is expressed as a set of claims is that you can determine where the data came from. The Issuer property for all the claims shown in the table is set to LOCAL AUTHORITY, which indicates that the user’s identity has been established by the application. 当这种信息被表示成一组声明(Claims)时的差别是,你能够确定这些数据是从哪里来的。表中所显示的所有声明的Issuer属性(发布者)都被设置到了LOACL AUTHORITY(本地授权),这说明该用户的标识是由应用程序建立的。 So, now that you have seen some example claims, I can more easily describe what a claim is. A claim is any piece of information about a user that is available to the application, including the user’s identity and role memberships. And, as you have seen, the information I have been defining about my users in earlier chapters is automatically made available as claims by ASP.NET Identity. 因此,现在你已经看到了一些声明(Claims)示例,我可以更容易地描述声明(Claim)是什么了。一项声明(Claim)是可用于应用程序中的有关用户的一个信息片段,包括用户的标识以及角色成员等。而且,正如你所看到的,我在前几章定义的关于用户的信息,被ASP.NET Identity自动地作为声明(Claims)了。 15.3.2 Creating and Using Claims 15.3.2 创建和使用声明(Claims) Claims are interesting for two reasons. The first reason is that an application can obtain claims from multiple sources, rather than just relying on a local database for information about the user. You will see a real example of this when I show you how to authenticate users through a third-party system in the “Using Third-Party Authentication” section, but for the moment I am going to add a class to the example project that simulates a system that provides claims information. Listing 15-15 shows the contents of the LocationClaimsProvider.cs file that I added to the Infrastructure folder. 声明(Claims)比较有意思的原因有两个。第一个原因是应用程序可以从多个来源获取声明(Claims),而不是只能依靠本地数据库关于用户的信息。你将会看到一个实际的示例,在“使用第三方认证”小节中,将演示如何通过第三方系统来认证用户。不过,此刻我只打算在示例项目中添加一个类,用以模拟一个提供声明(Claims)信息的系统。清单15-15显示了我添加到Infrastructure文件夹中LocationClaimsProvider.cs文件的内容。 Listing 15-15. The Contents of the LocationClaimsProvider.cs File 清单15-15. LocationClaimsProvider.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public static class LocationClaimsProvider {public static IEnumerable<Claim> GetClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.Name.ToLower() == "alice") {claims.Add(CreateClaim(ClaimTypes.PostalCode, "DC 20500"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "DC"));} else {claims.Add(CreateClaim(ClaimTypes.PostalCode, "NY 10036"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "NY"));}return claims;}private static Claim CreateClaim(string type, string value) {return new Claim(type, value, ClaimValueTypes.String, "RemoteClaims");} }} The GetClaims method takes a ClaimsIdentity argument and uses the Name property to create claims about the user’s ZIP code and state. This class allows me to simulate a system such as a central HR database, which would be the authoritative source of location information about staff, for example. GetClaims方法以ClaimsIdentity为参数,并使用Name属性创建了关于用户ZIP码(邮政编码)和州府的声明(Claims)。上述这个类使我能够模拟一个诸如中心化的HR数据库(人力资源数据库)之类的系统,它可能会成为全体职员的地点信息的权威数据源。 Claims are associated with the user’s identity during the authentication process, and Listing 15-16 shows the changes I made to the Login action method of the Account controller to call the LocationClaimsProvider class. 在认证过程期间,声明(Claims)是与用户标识关联在一起的,清单15-16显示了我对Account控制器中Login动作方法所做的修改,以便调用LocationClaimsProvider类。 Listing 15-16. Associating Claims with a User in the AccountController.cs File 清单15-16. AccountController.cs文件中用户用声明的关联 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... You can see the effect of the location claims by starting the application, authenticating as a user, and requesting the /Claim/Index URL. Figure 15-6 shows the claims for Alice. You may have to sign out and sign back in again to see the change. 为了看看这个地点声明(Claims)的效果,可以启动应用程序,以一个用户进行认证,并请求/Claim/Index URL。图15-6显示了Alice的声明(Claims)。你可能需要退出,然后再次登录才会看到发生的变化。 Figure 15-6. Defining additional claims for users 图15-6. 定义用户的附加声明 Obtaining claims from multiple locations means that the application doesn’t have to duplicate data that is held elsewhere and allows integration of data from external parties. The Claim.Issuer property tells you where a claim originated from, which helps you judge how accurate the data is likely to be and how much weight you should give the data in your application. Location data obtained from a central HR database is likely to be more accurate and trustworthy than data obtained from an external mailing list provider, for example. 从多个地点获取声明(Claims)意味着应用程序不必复制其他地方保持的数据,并且能够与外部的数据集成。Claim.Issuer属性(图15-6中的Issuer数据列——译者注)能够告诉你一个声明(Claim)的发源地,这有助于让你判断数据的精确程度,也有助于让你决定这类数据在应用程序中的权重。例如,从中心化的HR数据库获取的地点数据可能要比外部邮件列表提供器获取的数据更为精确和可信。 1. Applying Claims 1. 运用声明(Claims) The second reason that claims are interesting is that you can use them to manage user access to your application more flexibly than with standard roles. The problem with roles is that they are static, and once a user has been assigned to a role, the user remains a member until explicitly removed. This is, for example, how long-term employees of big corporations end up with incredible access to internal systems: They are assigned the roles they require for each new job they get, but the old roles are rarely removed. (The unexpectedly broad systems access sometimes becomes apparent during the investigation into how someone was able to ship the contents of the warehouse to their home address—true story.) 声明(Claims)有意思的第二个原因是,你可以用它们来管理用户对应用程序的访问,这要比标准的角色管理更为灵活。角色的问题在于它们是静态的,而且一旦用户已经被赋予了一个角色,该用户便是一个成员,直到明确地删除为止。例如,这意味着大公司的长期雇员,对内部系统的访问会十分惊人:他们每次在获得新工作时,都会赋予所需的角色,但旧角色很少被删除。(在调查某人为何能够将仓库里的东西发往他的家庭地址过程中发现,有时会出现异常宽泛的系统访问——真实的故事) Claims can be used to authorize users based directly on the information that is known about them, which ensures that the authorization changes when the data changes. The simplest way to do this is to generate Role claims based on user data that are then used by controllers to restrict access to action methods. Listing 15-17 shows the contents of the ClaimsRoles.cs file that I added to the Infrastructure. 声明(Claims)可以直接根据用户已知的信息对用户进行授权,这能够保证当数据发生变化时,授权也随之而变。此事最简单的做法是根据用户数据来生成Role声明(Claim),然后由控制器用来限制对动作方法的访问。清单15-17显示了我添加到Infrastructure中的ClaimsRoles.cs文件的内容。 Listing 15-17. The Contents of the ClaimsRoles.cs File 清单15-17. ClaimsRoles.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public class ClaimsRoles {public static IEnumerable<Claim> CreateRolesFromClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.HasClaim(x => x.Type == ClaimTypes.StateOrProvince&& x.Issuer == "RemoteClaims" && x.Value == "DC")&& user.HasClaim(x => x.Type == ClaimTypes.Role&& x.Value == "Employees")) {claims.Add(new Claim(ClaimTypes.Role, "DCStaff"));}return claims;} }} The gnarly looking CreateRolesFromClaims method uses lambda expressions to determine whether the user has a StateOrProvince claim from the RemoteClaims issuer with a value of DC and a Role claim with a value of Employees. If the user has both claims, then a Role claim is returned for the DCStaff role. Listing 15-18 shows how I call the CreateRolesFromClaims method from the Login action in the Account controller. CreateRolesFromClaims是一个粗糙的考察方法,它使用了Lambda表达式,以检查用户是否具有StateOrProvince声明(Claim),该声明来自于RemoteClaims发行者(Issuer),值为DC。也检查用户是否具有Role声明(Claim),其值为Employees。如果用户这两个声明都有,那么便返回一个DCStaff角色的Role声明。清单15-18显示了如何在Account控制器中的Login动作中调用CreateRolesFromClaims方法。 Listing 15-18. Generating Roles Based on Claims in the AccountController.cs File 清单15-18. 在AccountController.cs中根据声明生成角色 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(LocationClaimsProvider.GetClaims(ident)); ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... I can then restrict access to an action method based on membership of the DCStaff role. Listing 15-19 shows a new action method I added to the Claims controller to which I have applied the Authorize attribute. 然后我可以根据DCStaff角色的成员,来限制对一个动作方法的访问。清单15-19显示了在Claims控制器中添加的一个新的动作方法,在该方法上已经运用了Authorize注解属性。 Listing 15-19. Adding a New Action Method to the ClaimsController.cs File 清单15-19. 在ClaimsController.cs文件中添加一个新的动作方法 using System.Security.Claims;using System.Web;using System.Web.Mvc;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [Authorize(Roles="DCStaff")]public string OtherAction() {return "This is the protected action";} }} Users will be able to access OtherAction only if their claims grant them membership to the DCStaff role. Membership of this role is generated dynamically, so a change to the user’s employment status or location information will change their authorization level. 只要用户的声明(Claims)承认他们是DCStaff角色的成员,那么他们便能访问OtherAction动作。该角色的成员是动态生成的,因此,若是用户的雇用状态或地点信息发生变化,也会改变他们的授权等级。 提示:请读者从这个例子中吸取其中的思想精髓。对于读物的理解程度,仁者见仁,智者见智,能领悟多少,全凭各人,译者感觉这里的思想有无数的可能。举例说明:(1)可以根据用户的身份进行授权,比如学生在校时是“学生”,毕业后便是“校友”;(2)可以根据用户所处的部门进行授权,人事部用户属于人事团队,销售部用户属于销售团队,各团队有其自己的应用;(3)下一小节的示例是根据用户的地点授权。简言之:一方面用户的各种声明(Claim)都可以用来进行授权;另一方面用户的声明(Claim)又是可以自定义的。于是可能的运用就无法估计了。总之一句话,这种基于声明的授权(Claims-Based Authorization)有无限可能!要是没有我这里的提示,是否所有读者在此处都会有所体会?——译者注 15.3.3 Authorizing Access Using Claims 15.3.3 使用声明(Claims)授权访问 The previous example is an effective demonstration of how claims can be used to keep authorizations fresh and accurate, but it is a little indirect because I generate roles based on claims data and then enforce my authorization policy based on the membership of that role. A more direct and flexible approach is to enforce authorization directly by creating a custom authorization filter attribute. Listing 15-20 shows the contents of the ClaimsAccessAttribute.cs file, which I added to the Infrastructure folder and used to create such a filter. 前面的示例有效地演示了如何用声明(Claims)来保持新鲜和准确的授权,但有点不太直接,因为我要根据声明(Claims)数据来生成了角色,然后强制我的授权策略基于角色成员。一个更直接且灵活的办法是直接强制授权,其做法是创建一个自定义的授权过滤器注解属性。清单15-20演示了ClaimsAccessAttribute.cs文件的内容,我将它添加在Infrastructure文件夹中,并用它创建了这种过滤器。 Listing 15-20. The Contents of the ClaimsAccessAttribute.cs File 清单15-20. ClaimsAccessAttribute.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Infrastructure {public class ClaimsAccessAttribute : AuthorizeAttribute {public string Issuer { get; set; }public string ClaimType { get; set; }public string Value { get; set; }protected override bool AuthorizeCore(HttpContextBase context) {return context.User.Identity.IsAuthenticated&& context.User.Identity is ClaimsIdentity&& ((ClaimsIdentity)context.User.Identity).HasClaim(x =>x.Issuer == Issuer && x.Type == ClaimType && x.Value == Value);} }} The attribute I have defined is derived from the AuthorizeAttribute class, which makes it easy to create custom authorization policies in MVC framework applications by overriding the AuthorizeCore method. My implementation grants access if the user is authenticated, the IIdentity implementation is an instance of ClaimsIdentity, and the user has a claim with the issuer, type, and value matching the class properties. Listing 15-21 shows how I applied the attribute to the Claims controller to authorize access to the OtherAction method based on one of the location claims created by the LocationClaimsProvider class. 我所定义的这个注解属性派生于AuthorizeAttribute类,通过重写AuthorizeCore方法,很容易在MVC框架应用程序中创建自定义的授权策略。在这个实现中,若用户是已认证的、其IIdentity实现是一个ClaimsIdentity实例,而且该用户有一个带有issuer、type以及value的声明(Claim),它们与这个类的属性是匹配的,则该用户便是允许访问的。清单15-21显示了如何将这个注解属性运用于Claims控制器,以便根据LocationClaimsProvider类创建的地点声明(Claim),对OtherAction方法进行授权访问。 Listing 15-21. Performing Authorization on Claims in the ClaimsController.cs File 清单15-21. 在ClaimsController.cs文件中执行基于声明的授权 using System.Security.Claims;using System.Web;using System.Web.Mvc;using Users.Infrastructure;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [ClaimsAccess(Issuer="RemoteClaims", ClaimType=ClaimTypes.PostalCode,Value="DC 20500")]public string OtherAction() {return "This is the protected action";} }} My authorization filter ensures that only users whose location claims specify a ZIP code of DC 20500 can invoke the OtherAction method. 这个授权过滤器能够确保只有地点声明(Claim)的邮编为DC 20500的用户才能请求OtherAction方法。 15.4 Using Third-Party Authentication 15.4 使用第三方认证 One of the benefits of a claims-based system such as ASP.NET Identity is that any of the claims can come from an external system, even those that identify the user to the application. This means that other systems can authenticate users on behalf of the application, and ASP.NET Identity builds on this idea to make it simple and easy to add support for authenticating users through third parties such as Microsoft, Google, Facebook, and Twitter. 基于声明的系统,如ASP.NET Identity,的好处之一是任何声明都可以来自于外部系统,即使是将用户标识到应用程序的那些声明。这意味着其他系统可以代表应用程序来认证用户,而ASP.NET Identity就建立在这样的思想之上,使之能够简单而方便地添加第三方认证用户的支持,如微软、Google、Facebook、Twitter等。 There are some substantial benefits of using third-party authentication: Many users will already have an account, users can elect to use two-factor authentication, and you don’t have to manage user credentials in the application. In the sections that follow, I’ll show you how to set up and use third-party authentication for Google users, which Table 15-8 puts into context. 使用第三方认证有一些实际的好处:许多用户已经有了账号、用户可以选择使用双因子认证、你不必在应用程序中管理用户凭据等等。在以下小节中,我将演示如何为Google用户建立并使用第三方认证,表15-8描述了事情的情形。 Table 15-8. Putting Third-Party Authentication in Context 表15-8. 第三方认证情形 Question 问题 Answer 回答 What is it? 什么是第三方认证? Authenticating with third parties lets you take advantage of the popularity of companies such as Google and Facebook. 第三方认证使你能够利用流行公司,如Google和Facebook,的优势。 Why should I care? 为何要关心它? Users don’t like having to remember passwords for many different sites. Using a provider with large-scale adoption can make your application more appealing to users of the provider’s services. 用户不喜欢记住许多不同网站的口令。使用大范围适应的提供器可使你的应用程序更吸引有提供器服务的用户。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework. 这不是一个直接由MVC框架使用的特性。 Note The reason I have chosen to demonstrate Google authentication is that it is the only option that doesn’t require me to register my application with the authentication service. You can get details of the registration processes required at http://bit.ly/1cqLTrE. 提示:我选择演示Google认证的原因是,它是唯一不需要在其认证服务中注册我应用程序的公司。有关认证服务注册过程的细节,请参阅http://bit.ly/1cqLTrE。 15.4.1 Enabling Google Authentication 15.4.1 启用Google认证 ASP.NET Identity comes with built-in support for authenticating users through their Microsoft, Google, Facebook, and Twitter accounts as well more general support for any authentication service that supports OAuth. The first step is to add the NuGet package that includes the Google-specific additions for ASP.NET Identity. Enter the following command into the Package Manager Console: ASP.NET Identity带有通过Microsoft、Google、Facebook以及Twitter账号认证用户的内建支持,并且对于支持OAuth的认证服务具有更普遍的支持。第一个步骤是添加NuGet包,包中含有用于ASP.NET Identity的Google专用附件。请在“Package Manager Console(包管理器控制台)”中输入以下命令: Install-Package Microsoft.Owin.Security.Google -version 2.0.2 There are NuGet packages for each of the services that ASP.NET Identity supports, as described in Table 15-9. 对于ASP.NET Identity支持的每一种服务都有相应的NuGet包,如表15-9所示。 Table 15-9. The NuGet Authenticaton Packages 表15-9. NuGet认证包 Name 名称 Description 描述 Microsoft.Owin.Security.Google Authenticates users with Google accounts 用Google账号认证用户 Microsoft.Owin.Security.Facebook Authenticates users with Facebook accounts 用Facebook账号认证用户 Microsoft.Owin.Security.Twitter Authenticates users with Twitter accounts 用Twitter账号认证用户 Microsoft.Owin.Security.MicrosoftAccount Authenticates users with Microsoft accounts 用Microsoft账号认证用户 Microsoft.Owin.Security.OAuth Authenticates users against any OAuth 2.0 service 根据任一OAuth 2.0服务认证用户 Once the package is installed, I enable support for the authentication service in the OWIN startup class, which is defined in the App_Start/IdentityConfig.cs file in the example project. Listing 15-22 shows the change that I have made. 一旦安装了这个包,便可以在OWIN启动类中启用此项认证服务的支持,启动类的定义在示例项目的App_Start/IdentityConfig.cs文件中。清单15-22显示了所做的修改。 Listing 15-22. Enabling Google Authentication in the IdentityConfig.cs File 清单15-22. 在IdentityConfig.cs文件中启用Google认证 using Microsoft.AspNet.Identity;using Microsoft.Owin;using Microsoft.Owin.Security.Cookies;using Owin;using Users.Infrastructure;using Microsoft.Owin.Security.Google;namespace Users {public class IdentityConfig {public void Configuration(IAppBuilder app) {app.CreatePerOwinContext<AppIdentityDbContext>(AppIdentityDbContext.Create);app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions {AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,LoginPath = new PathString("/Account/Login"),}); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);app.UseGoogleAuthentication();} }} Each of the packages that I listed in Table 15-9 contains an extension method that enables the corresponding service. The extension method for the Google service is called UseGoogleAuthentication, and it is called on the IAppBuilder implementation that is passed to the Configuration method. 表15-9所列的每个包都含有启用相应服务的扩展方法。用于Google服务的扩展方法名称为UseGoogleAuthentication,它通过传递给Configuration方法的IAppBuilder实现进行调用。 Next I added a button to the Views/Account/Login.cshtml file, which allows users to log in via Google. You can see the change in Listing 15-23. 下一步骤是在Views/Account/Login.cshtml文件中添加一个按钮,让用户能够通过Google进行登录。所做的修改如清单15-23所示。 Listing 15-23. Adding a Google Login Button to the Login.cshtml File 清单15-23. 在Login.cshtml文件中添加Google登录按钮 @model Users.Models.LoginModel@{ ViewBag.Title = "Login";}<h2>Log In</h2> @Html.ValidationSummary()@using (Html.BeginForm()) {@Html.AntiForgeryToken();<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><div class="form-group"><label>Name</label>@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })</div><div class="form-group"><label>Password</label>@Html.PasswordFor(x => x.Password, new { @class = "form-control" })</div><button class="btn btn-primary" type="submit">Log In</button>}@using (Html.BeginForm("GoogleLogin", "Account")) {<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><button class="btn btn-primary" type="submit">Log In via Google</button>} The new button submits a form that targets the GoogleLogin action on the Account controller. You can see this method—and the other changes I made the controller—in Listing 15-24. 新按钮递交一个表单,目标是Account控制器中的GoogleLogin动作。可从清单15-24中看到该方法,以及在控制器中所做的其他修改。 Listing 15-24. Adding Support for Google Authentication to the AccountController.cs File 清单15-24. 在AccountController.cs文件中添加Google认证支持 using System.Threading.Tasks;using System.Web.Mvc;using Users.Models;using Microsoft.Owin.Security;using System.Security.Claims;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Infrastructure;using System.Web; namespace Users.Controllers {[Authorize]public class AccountController : Controller {[AllowAnonymous]public ActionResult Login(string returnUrl) {if (HttpContext.User.Identity.IsAuthenticated) {return View("Error", new string[] { "Access Denied" });}ViewBag.returnUrl = returnUrl;return View();}[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident)); AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);} [HttpPost][AllowAnonymous]public ActionResult GoogleLogin(string returnUrl) {var properties = new AuthenticationProperties {RedirectUri = Url.Action("GoogleLoginCallback",new { returnUrl = returnUrl})};HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();}[AllowAnonymous]public async Task<ActionResult> GoogleLoginCallback(string returnUrl) {ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();AppUser user = await UserManager.FindAsync(loginInfo.Login);if (user == null) {user = new AppUser {Email = loginInfo.Email,UserName = loginInfo.DefaultUserName,City = Cities.LONDON, Country = Countries.UK};IdentityResult result = await UserManager.CreateAsync(user);if (!result.Succeeded) {return View("Error", result.Errors);} else {result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);if (!result.Succeeded) {return View("Error", result.Errors);} }}ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false }, ident);return Redirect(returnUrl ?? "/");}[Authorize]public ActionResult Logout() {AuthManager.SignOut();return RedirectToAction("Index", "Home");}private IAuthenticationManager AuthManager {get {return HttpContext.GetOwinContext().Authentication;} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } The GoogleLogin method creates an instance of the AuthenticationProperties class and sets the RedirectUri property to a URL that targets the GoogleLoginCallback action in the same controller. The next part is a magic phrase that causes ASP.NET Identity to respond to an unauthorized error by redirecting the user to the Google authentication page, rather than the one defined by the application: GoogleLogin方法创建了AuthenticationProperties类的一个实例,并为RedirectUri属性设置了一个URL,其目标为同一控制器中的GoogleLoginCallback动作。下一个部分是一个神奇阶段,通过将用户重定向到Google认证页面,而不是应用程序所定义的认证页面,让ASP.NET Identity对未授权的错误进行响应: ...HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();... This means that when the user clicks the Log In via Google button, their browser is redirected to the Google authentication service and then redirected back to the GoogleLoginCallback action method once they are authenticated. 这意味着,当用户通过点击Google按钮进行登录时,浏览器被重定向到Google的认证服务,一旦在那里认证之后,便被重定向回GoogleLoginCallback动作方法。 I get details of the external login by calling the GetExternalLoginInfoAsync of the IAuthenticationManager implementation, like this: 我通过调用IAuthenticationManager实现的GetExternalLoginInfoAsync方法,我获得了外部登录的细节,如下所示: ...ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();... The ExternalLoginInfo class defines the properties shown in Table 15-10. ExternalLoginInfo类定义的属性如表15-10所示: Table 15-10. The Properties Defined by the ExternalLoginInfo Class 表15-10. ExternalLoginInfo类所定义的属性 Name 名称 Description 描述 DefaultUserName Returns the username 返回用户名 Email Returns the e-mail address 返回E-mail地址 ExternalIdentity Returns a ClaimsIdentity that identities the user 返回标识该用户的ClaimsIdentity Login Returns a UserLoginInfo that describes the external login 返回描述外部登录的UserLoginInfo I use the FindAsync method defined by the user manager class to locate the user based on the value of the ExternalLoginInfo.Login property, which returns an AppUser object if the user has been authenticated with the application before: 我使用了由用户管理器类所定义的FindAsync方法,以便根据ExternalLoginInfo.Login属性的值对用户进行定位,如果用户之前在应用程序中已经认证,该属性会返回一个AppUser对象: ...AppUser user = await UserManager.FindAsync(loginInfo.Login);... If the FindAsync method doesn’t return an AppUser object, then I know that this is the first time that this user has logged into the application, so I create a new AppUser object, populate it with values, and save it to the database. I also save details of how the user logged in so that I can find them next time: 如果FindAsync方法返回的不是AppUser对象,那么我便知道这是用户首次登录应用程序,于是便创建了一个新的AppUser对象,填充该对象的值,并将其保存到数据库。我还保存了用户如何登录的细节,以便下次能够找到他们: ...result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);... All that remains is to generate an identity the user, copy the claims provided by Google, and create an authentication cookie so that the application knows the user has been authenticated: 剩下的事情只是生成该用户的标识了,拷贝Google提供的声明(Claims),并创建一个认证Cookie,以使应用程序知道此用户已认证: ...ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);... 15.4.2 Testing Google Authentication 15.4.2 测试Google认证 There is one further change that I need to make before I can test Google authentication: I need to change the account verification I set up in Chapter 13 because it prevents accounts from being created with e-mail addresses that are not within the example.com domain. Listing 15-25 shows how I removed the verification from the AppUserManager class. 在测试Google认证之前还需要一处修改:需要修改第13章所建立的账号验证,因为它不允许example.com域之外的E-mail地址创建账号。清单15-25显示了如何在AppUserManager类中删除这种验证。 Listing 15-25. Disabling Account Validation in the AppUserManager.cs File 清单15-25. 在AppUserManager.cs文件中取消账号验证 using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Microsoft.AspNet.Identity.Owin;using Microsoft.Owin;using Users.Models; namespace Users.Infrastructure {public class AppUserManager : UserManager<AppUser> {public AppUserManager(IUserStore<AppUser> store): base(store) {}public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options,IOwinContext context) {AppIdentityDbContext db = context.Get<AppIdentityDbContext>();AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db)); manager.PasswordValidator = new CustomPasswordValidator {RequiredLength = 6,RequireNonLetterOrDigit = false,RequireDigit = false,RequireLowercase = true,RequireUppercase = true}; //manager.UserValidator = new CustomUserValidator(manager) {// AllowOnlyAlphanumericUserNames = true,// RequireUniqueEmail = true//};return manager;} }} Tip you can use validation for externally authenticated accounts, but I am just going to disable the feature for simplicity. 提示:也可以使用外部已认证账号的验证,但这里出于简化,取消了这一特性。 To test authentication, start the application, click the Log In via Google button, and provide the credentials for a valid Google account. When you have completed the authentication process, your browser will be redirected back to the application. If you navigate to the /Claims/Index URL, you will be able to see how claims from the Google system have been added to the user’s identity, as shown in Figure 15-7. 为了测试认证,启动应用程序,通过点击“Log In via Google(通过Google登录)”按钮,并提供有效的Google账号凭据。当你完成了认证过程时,浏览器将被重定向回应用程序。如果导航到/Claims/Index URL,便能够看到来自Google系统的声明(Claims),已被添加到用户的标识中了,如图15-7所示。 Figure 15-7. Claims from Google 图15-7. 来自Google的声明(Claims) 15.5 Summary 15.5 小结 In this chapter, I showed you some of the advanced features that ASP.NET Identity supports. I demonstrated the use of custom user properties and how to use database migrations to preserve data when you upgrade the schema to support them. I explained how claims work and how they can be used to create more flexible ways of authorizing users. I finished the chapter by showing you how to authenticate users via Google, which builds on the ideas behind the use of claims. 本章向你演示了ASP.NET Identity所支持的一些高级特性。演示了自定义用户属性的使用,还演示了在升级数据架构时,如何使用数据库迁移保护数据。我解释了声明(Claims)的工作机制,以及如何将它们用于创建更灵活的用户授权方式。最后演示了如何通过Google进行认证结束了本章,这是建立在使用声明(Claims)的思想基础之上的。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gz19871113/article/details/108591802。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-28 08:49:21
283
转载
ClickHouse
ClickHouse与NodeNotReadyException:深入理解及解决策略 1. 引言 在大数据时代,ClickHouse作为一款高性能、列式存储的开源SQL数据库管理系统,受到了业界的广泛关注和广泛应用。然而,在实际使用过程中,我们可能会遇到“NodeNotReadyException:节点未准备好异常”这样的问题,这对于初次接触或深度使用ClickHouse的开发者来说,无疑是一次挑战。这篇文章会手把手地带你们钻进这个问题的本质里头,咱们一起通过实实在在的例子把它掰开揉碎了瞧,顺便还会送上解决之道! 2. NodeNotReadyException 现象与原因剖析 “NodeNotReadyException:节点未准备好异常”,顾名思义,是指在对ClickHouse集群中的某个节点进行操作时,该节点尚未达到可以接受请求的状态。这种状况可能是因为节点正在经历重启啊、恢复数据啦、同步副本这些阶段,或者也可能是配置出岔子了,又或者是网络闹脾气、出现问题啥的,给整出来的。 例如,当我们尝试从一个正在启动或者初始化中的节点查询数据时,可能会收到如下错误信息: java try { clickHouseClient.execute("SELECT FROM my_table"); } catch (Exception e) { if (e instanceof NodeNotReadyException) { System.out.println("Caught a NodeNotReadyException: " + e.getMessage()); } } 上述代码中,如果执行查询的ClickHouse节点恰好处于未就绪状态,就会抛出NodeNotReadyException异常。 3. 深入排查与应对措施 (1)检查节点状态 首先,我们需要登录到出现问题的节点,查看其运行状态。可以通过system.clusters表来获取集群节点状态信息: sql SELECT FROM system.clusters; 观察结果中对应节点的is_alive字段是否为1,如果不是,则表示该节点可能存在问题。 (2)日志分析 其次,查阅ClickHouse节点的日志文件(默认路径通常在 /var/log/clickhouse-server/),寻找可能导致节点未准备好的线索,如重启记录、同步失败等信息。 (3)配置核查 检查集群配置文件(如 config.xml 和 users.xml),确认节点间的网络通信、数据复制等相关设置是否正确无误。 (4)网络诊断 排除节点间网络连接的问题,确保各个节点之间的网络是通畅的。可以通过ping命令或telnet工具来测试。 (5)故障转移与恢复 针对分布式场景,合理利用ClickHouse的分布式表引擎特性,设计合理的故障转移策略,当出现节点未就绪时,能自动切换到其他可用节点。 4. 预防与优化策略 - 定期维护与监控:建立完善的监控系统,实时检测每个节点的运行状况,并对可能出现问题的节点提前预警。 - 合理规划集群规模与架构:根据业务需求,合理规划集群规模,避免单点故障,同时确保各节点负载均衡。 - 升级与补丁管理:及时关注ClickHouse的版本更新与安全补丁,确保所有节点保持最新稳定版本,降低因软件问题引发的NodeNotReadyException风险。 - 备份与恢复策略:制定有效的数据备份与恢复方案,以便在节点发生故障时,能够快速恢复服务。 总结起来,面对ClickHouse的NodeNotReadyException异常,我们不仅需要深入理解其背后的原因,更要在实践中掌握一套行之有效的排查方法和预防策略。这样子做,才能确保当我们的大数据处理平台碰上这类问题时,仍然能够坚如磐石地稳定运行,实实在在地保障业务的连贯性不受影响。这一切的一切,都离不开我们对技术细节的死磕和实战演练的过程,这正是我们在大数据这个领域不断进步、持续升级的秘密武器。
2024-02-20 10:58:16
494
月影清风
ClickHouse
如何配置ClickHouse的数据中心以满足特定需求? 在大数据时代,ClickHouse作为一款高性能的列式数据库管理系统,以其出色的查询速度和处理能力赢得了众多企业的青睐。然而,为了让ClickHouse数据中心彻底展现它的威力,并且完美适应特定业务环境的需求,我们得给它来个“量体裁衣”式的精细设置。嘿,伙计们,这篇内容将会手把手地带你们踏上一段实战之旅,咱们一步步地通过具体的步骤和鲜活的代码实例,来揭开如何搭建一个既高效又稳定的ClickHouse数据中心的秘密面纱。 1. 确定硬件配置与集群架构 首先,我们从硬件配置和集群设计开始。根据业务的具体需求,数据量大小和并发查询的压力等因素,就像指挥棒一样,会直接影响到我们选择硬件资源的规格以及集群结构的设计布局。比如说,如果我们的业务需要处理海量数据或者面临大量的并发查询挑战,那就得像搭积木一样,精心设计和构建强大的硬件支撑体系以及合理的集群架构,才能确保整个系统的稳定高效运行。 例如,如果您的业务涉及到PB级别的海量数据存储和实时分析,可能需要考虑采用分布式集群部署的方式,每个节点配置较高的CPU核心数、大内存以及高速SSD硬盘: yaml 配置文件(/etc/clickhouse-server/config.xml) true node1.example.com 9000 这里展示了如何配置一个多副本、多分片的ClickHouse集群。my_cluster是集群名称,内部包含多个shard,每个shard又包含多个replica,确保了高可用性和容错性。 2. 数据分区策略与表引擎选择 ClickHouse支持多种表引擎,如MergeTree系列,这对于数据分区和优化查询性能至关重要。以MergeTree为例,我们可以根据时间戳或其他业务关键字段进行分区: sql CREATE TABLE my_table ( id Int64, timestamp DateTime, data String ) ENGINE = MergeTree() PARTITION BY toYYYYMMDD(timestamp) ORDER BY (timestamp, id); 上述SQL语句创建了一个名为my_table的表,使用MergeTree引擎,并按照timestamp字段进行分区,按timestamp和id排序,这有助于提高针对时间范围的查询效率。 3. 调优配置参数 ClickHouse提供了一系列丰富的配置参数以适应不同的工作负载。比如,对于写入密集型场景,可以调整以下参数: yaml 1048576 增大插入块大小 16 调整后台线程池大小 16 最大并行查询线程数 这些参数可以根据实际服务器性能和业务需求进行适当调整,以达到最优写入性能。 4. 监控与运维管理 为了保证ClickHouse数据中心的稳定运行,必须配备完善的监控系统。ClickHouse自带Prometheus metrics exporter,方便集成各类监控工具: bash 启动Prometheus exporter clickhouse-server --metric_log_enabled=1 同时,合理规划备份与恢复策略,利用ClickHouse的备份工具或第三方工具实现定期备份,确保数据安全。 总结起来,配置ClickHouse数据中心是一个既需要深入理解技术原理,又需紧密结合业务实践的过程。当面对特定的需求时,我们得像玩转乐高积木一样,灵活运用ClickHouse的各种强大功能。从挑选合适的硬件设备开始,一步步搭建起集群架构,再到精心设计数据模型,以及日常的运维调优,每一个环节都不能落下,都要全面、细致地去琢磨和优化,确保整个系统运作流畅,高效满足需求。在这个过程中,我们得不断摸爬滚打、动动脑筋、灵活变通,才能让我们的ClickHouse数据中心持续进步,更上一层楼地为业务发展添砖加瓦、保驾护航。
2023-07-29 22:23:54
509
翡翠梦境
MySQL
...越多的企业采用自动化工具(如Ansible、Chef或Puppet)进行MySQL数据库的运维管理,包括自动备份恢复、监控告警、性能调优等任务,大大提高了工作效率和系统稳定性。 而对于深入学习MySQL的开发者和技术人员,建议阅读官方文档和社区发布的最新教程,了解如何在不同场景下利用MySQL命令行、Workbench图形工具或者PHPMyAdmin等第三方工具进行数据库设计、SQL查询优化以及权限管理等高级实践。同时,跟踪MySQL官方博客和社区论坛上的讨论,及时获取关于安全更新、补丁发布以及最佳实践的最新资讯,确保在享受MySQL强大功能的同时,能够紧跟时代步伐,应对不断变化的技术挑战。
2023-12-12 11:10:15
135
数据库专家
MySQL
...更高效便捷的数据处理工具(来源:MySQL官方网站,2022年发布)。同时,对于云端数据库的安全防护,云服务商如AWS、阿里云等也相继推出了针对MySQL数据库的安全策略和最佳实践指南,指导用户如何通过网络ACL、SSL加密连接、定期审计与备份等方式强化数据库安全(参考:AWS Security Blog, 阿里云最佳实践)。 此外,深入理解MySQL权限系统及其实战应用亦是每个数据库管理员的必修课。在实际操作中,精细化权限管理能有效防止数据泄露和恶意篡改,推荐阅读《MySQL 5.7 Reference Manual》中的“Account Management and Privileges”章节,该部分详细解读了MySQL的用户账户管理、权限分配及验证机制。 另外,随着DevOps理念的普及,自动化运维工具如Ansible和Chef被越来越多地应用于MySQL数据库的部署和维护。通过编写Playbook或Cookbook脚本,可以实现MySQL集群的快速搭建和动态扩容,以及日常备份恢复任务的自动化执行,这对于大规模云端数据库环境的运维管理工作具有重大意义(参阅:Ansible官方文档,Chef Cookbooks示例)。 总之,在安装配置MySQL作为云端数据库之后,关注其最新版本特性、加强安全措施、深入理解权限体系,并利用自动化运维工具提高效率,都是保障数据库稳定运行、发挥其最大价值的关键所在。
2023-10-24 11:08:12
58
逻辑鬼才
MySQL
...至RDS,并实现无缝备份与恢复的实战经验,为众多寻求上云解决方案的企业提供了宝贵参考。 不仅如此,对于希望深入理解MySQL内部机制的开发者,Stack Overflow上有资深专家撰写了系列教程,详尽解析了InnoDB存储引擎的工作原理,以及SQL查询优化技巧,帮助读者提升数据库设计与运维水平。 总之,在掌握MySQL基本使用的基础上,持续跟进技术发展动态,深入了解并实践高级功能与安全管理措施,是确保MySQL数据库在各类型应用程序中稳定高效运行的关键。
2023-02-05 14:43:17
74
程序媛
MySQL
...SQL服务提供了一键备份恢复、读写分离、自动扩展等功能,为系统数据的高效管理和高可用性提供了有力支持。 再者,深入探讨MySQL在大数据处理领域的应用也不容忽视。虽然MySQL传统上主要用于OLTP在线交易处理场景,但在结合Hadoop、Spark等大数据框架后,也能够实现大规模数据分析和处理。比如使用Apache Sqoop工具将MySQL数据导入HDFS,或通过JDBC连接Spark SQL对MySQL数据进行复杂分析。 此外,对于系统安全性的考虑,如何有效防止SQL注入、实施权限管理以及加密敏感数据也是MySQL使用者需要关注的重点。MySQL自带的多层访问控制机制及密码加密策略可确保数据安全性,同时,业界还推荐遵循OWASP SQL注入防护指南来编写安全的SQL查询语句。 总之,在实际工作中,熟练掌握MySQL并结合最新的技术趋势与最佳实践,将有助于构建更为稳定、高效且安全的系统数据存储解决方案。
2023-01-17 16:44:32
123
程序媛
.net
...件流处理机制及其应用实践后,我们可以进一步关注现代软件开发中数据流处理的最新趋势和应用场景。随着云计算、大数据和微服务架构的发展,文件流处理技术正逐渐向分布式和流式计算方向演进。 例如,Azure Data Factory等云服务提供了高效的数据流处理功能,开发者可以基于.Net框架构建数据管道,实现大规模文件数据的读取、转换和加载,极大地提升了数据处理效率与灵活性。此外,.NET Core 3.0及更高版本引入了对异步IO操作的增强支持,使得文件流在处理大文件或高并发场景时能够更好地发挥性能优势,降低系统延迟。 同时,实时日志分析、持续集成/持续部署(CI/CD)流程中的文件流转存、以及数据库备份恢复等实际场景,都离不开文件流技术的深度应用。因此,掌握好文件流处理不仅对于日常编程工作至关重要,也是紧跟技术潮流、解决复杂业务问题的重要能力体现。建议读者结合具体业务需求,探索更多高级特性,如内存映射文件(Memory-Mapped Files)以提升处理超大型文件的效能,或者利用.NET的并行文件系统(parallel file system)接口优化多线程环境下的文件访问性能。
2023-05-01 08:51:54
468
岁月静好
Hadoop
Hadoop中的数据备份与恢复策略 一、引言 随着大数据的发展,Hadoop已经成为一种非常流行的分布式计算框架。然而,在大数据处理过程中,数据的安全性和完整性是非常重要的。为了稳稳地保护好我们的数据安全,咱们得养成定期给数据做个“备胎”的习惯,这样万一碰上啥情况需要数据时,就能迅速又麻利地把它给找回来。这篇文章将介绍如何在Hadoop中实现数据备份和恢复。 二、数据备份策略 1. 完全备份 完全备份是一种最基本的备份策略,它是指备份整个系统的数据。在Hadoop中,我们可以使用HDFS的hdfs dfs -get命令来完成数据的完整备份。 例如: bash hdfs dfs -get /data/hadoop/data /backup/data 上述命令表示将HDFS目录/data/hadoop/data下的所有文件复制到本地目录/backup/data下。 优点:全面保护数据安全,可以避免因系统故障导致的数据丢失。 缺点:备份操作耗时较长,且在数据量大的情况下,占用大量存储空间。 2. 差异备份 差异备份是在已有备份的基础上,只备份自上次备份以来发生改变的部分数据。在用Hadoop的时候,我们有一个超好用的小工具叫Hadoop DistCp,它可以帮我们轻松实现数据的差异备份,就像是给大数据做个“瘦身”运动一样。 例如: css hadoop distcp hdfs://namenode:port/oldpath newpath 上述命令表示将HDFS目录oldpath下的所有文件复制到新路径newpath下。 优点:可以减少备份所需的时间和存储空间,提高备份效率。 缺点:如果已经有多个备份,则每次都需要比较和找出不同的部分进行备份,增加了备份的复杂性。 三、数据恢复策略 1. 点对点恢复 点对点恢复是指直接从原始存储设备上恢复数据,不需要经过任何中间环节。在Hadoop中,我们可以通过Hadoop自带的工具Hadoop fsck来实现数据恢复。 例如: bash hadoop fsck /data/hadoop/data 上述命令表示检查HDFS目录/data/hadoop/data下的所有文件是否完好。 优点:可以直接恢复原始数据,恢复速度快,不会因为中间环节出现问题而导致数据丢失。 缺点:只能用于单节点故障恢复,对于大规模集群无法有效应对。 2. 复制恢复 复制恢复是指通过备份的数据副本来恢复原始数据。在Hadoop中,我们可以使用Hadoop自带的工具Hadoop DistCp来实现数据恢复。 例如: bash hadoop distcp hdfs://namenode:port/source newpath 上述命令表示将HDFS目录source下的所有文件复制到新路径newpath下。 优点:可以用于大规模集群恢复,恢复速度较快,无需等待数据传输。 缺点:需要有足够的存储空间存放备份数据,且恢复过程中需要消耗较多的网络带宽。 四、结论 在Hadoop中实现数据备份和恢复是一个复杂的过程,需要根据实际情况选择合适的备份策略和恢复策略。同时呢,咱们也得把数据备份的频次和备份数据的质量这两点重视起来。想象一下,就像咱们定期存钱进小金库,而且每次存的都是真金白银,这样在遇到突发情况需要用到的时候,才能迅速又准确地把“财产”给找回来,对吧?所以,确保数据备份既及时又靠谱,关键时刻才能派上大用场。希望通过这篇文章,能让你对Hadoop中的数据备份和恢复有更深入的理解和认识。
2023-09-08 08:01:47
400
时光倒流-t
Etcd
...分布式系统存储和容灾备份的最新实践和发展趋势。近期,随着云原生架构的普及,Etcd作为Kubernetes等容器编排系统的基石,在集群状态管理和配置存储方面的重要性日益凸显。为了提升系统的稳定性和可用性,业界对于Etcd的数据保护策略、高可用设计以及灾难恢复方案的研究与实践不断深化。 例如,Google Cloud Platform团队近期发布了一篇关于Etcd存储层优化与故障恢复机制的深度分析报告,详尽阐述了如何通过改进snapshot策略、增强数据持久化能力以及实现跨地域多副本冗余,以降低由于硬件故障或网络问题导致的数据丢失风险。 同时,CNCF社区也正在积极推动Etcd项目的持续演进,包括对Raft一致性算法的优化、性能提升以及安全特性的增强等方面。针对Etcd的运维管理,有专业团队分享了实战经验,比如定期执行健康检查、监控关键指标,并结合自动化工具进行故障切换演练和备份恢复测试,确保在实际生产环境中能够快速有效地应对类似“Etcdserver无法从数据目录启动”的问题。 总之,理解并掌握Etcd的核心功能与运维要点,紧密跟踪其发展动态和技术前沿,对于构建和维护健壮高效的分布式系统具有重要的现实意义。
2023-01-07 12:31:32
512
岁月静好-t
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
watch -n 5 'command'
- 定时执行命令并刷新输出结果(每5秒一次)。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"