前端技术
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
[Hadoop与关系型数据库数据集成实践]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Redis
NoSQL数据库 , NoSQL(Not Only SQL)是一种非关系型数据库管理系统,它不同于传统的关系型数据库,不以表格的形式存储数据,而是采用多种灵活的数据模型如键值对、文档、列族和图形等。在本文中,Redis作为一种NoSQL数据库,因其支持多种数据结构和高效内存操作而广泛应用于缓存和消息中间件领域。 缓存 , 在计算机系统中,缓存是一种用于临时存储常用或最近使用过的数据的硬件或软件组件,旨在减少频繁访问较慢存储层(如硬盘)带来的性能开销。在本文上下文中,Redis被用作缓存系统时,可以快速提供热点数据,显著提高应用程序读取速度和整体响应能力。 分片策略 , 在分布式数据库系统中,分片(也称为分区)是一种将数据拆分成多个部分并分布在不同节点上的技术,以实现水平扩展和负载均衡。Redis Cluster通过内置的分片策略,可以根据特定算法(例如哈希槽分配)将数据均匀分散到各个节点上,从而有效提升系统的处理能力和可扩展性。
2023-06-18 19:56:23
273
幽谷听泉-t
Greenplum
一、引言 在大数据时代,推荐系统已经成为我们生活的一部分。无论是你在逛电商网站时看到的各种商品推荐,还是在音乐视频平台刷到的个性化内容推送,甚至是社交媒体上为你精心匹配的好友建议,可以说它们简直就是无处不在,充斥着我们的日常生活。然而,现如今啊,随着数据量蹭蹭地往上涨,怎么才能把这些海量数据吃得透透的,并且精准地给用户推送他们想要的东西,这可真成了我们眼前一道躲不过去的大难题了。 这就是我们要讨论的主题——使用Greenplum进行实时推荐系统开发。Greenplum这个家伙,是Pivotal公司家的明星产品,一款超级给力的分布式数据库系统。它特擅长对付那种海量数据,而且还能做到实时分析,就像个数据处理的超能勇士一样。 二、绿萍普的基本概念与特性 首先,我们需要了解什么是Greenplum。简单来说,Greenplum是一种基于PostgreSQL的关系型数据库管理系统。它具有以下特点: 1. 分布式架构 Greenplum采用了MPP(Massively Parallel Processing)架构,可以将数据分布在多个节点上进行处理,大大提高了处理速度。 2. 实时查询 Greenplum支持实时查询,可以在海量数据中快速找到需要的信息。 3. 高可用性 Greenplum采用了冗余设计,任何一个节点出现问题,都不会影响整个系统的运行。 三、Greenplum在实时推荐系统中的应用 接下来,我们将详细介绍如何使用Greenplum来构建一个实时推荐系统。 首先,我们需要收集用户的行为数据,如用户的浏览记录、购买记录等。这些数据可以通过日志文件、API接口等方式获取。 然后,我们可以使用Greenplum来存储和管理这些数据。比如说,我们可以动手建立一个用户行为记录表,就像个小本本一样,把用户的ID号码、干了啥类型的行为、啥时候干的这些小细节,都一五一十地记在这个表格里。 接着,我们需要计算用户的历史行为模式,以便于对用户进行个性化推荐。这可以通过一些机器学习算法来完成,如协同过滤、矩阵分解等。 最后,我们可以使用Greenplum来进行实时推荐。当有新的用户行为数据蹦出来的时候,我们能立马给用户行为表来个实时更新。接着,咱们通过一套算法“火速”算出用户的最新行为习惯,最后就能生成专属于他们的个性化推荐啦! 四、代码示例 下面是一段使用Greenplum进行实时推荐的代码示例: sql CREATE TABLE user_behavior ( user_id INT, behavior_type TEXT, behavior_time TIMESTAMP ); INSERT INTO user_behavior VALUES (1, 'view', '2021-01-01 00:00:00'); INSERT INTO user_behavior VALUES (1, 'buy', '2021-01-02 00:00:00'); INSERT INTO user_behavior VALUES (2, 'view', '2021-01-01 00:00:00'); -- 计算用户行为模式 SELECT user_id, behavior_type, COUNT() as frequency FROM user_behavior GROUP BY user_id, behavior_type; -- 实时推荐 INSERT INTO user_behavior VALUES (3, 'view', '2021-01-01 00:00:00'); SELECT u.user_id, m.product_id, m.rating FROM user_behavior u JOIN product_behavior b ON u.user_id = b.user_id AND u.behavior_type = b.behavior_type JOIN matrix m ON u.user_id = m.user_id AND b.product_id = m.product_id WHERE u.user_id = 3; 以上代码首先创建了一个用户行为表,然后插入了一些样本数据。然后,我们统计了大家的使用习惯频率,最后,根据每个人独特的行为模式,实时地给出了个性化的推荐内容~ 五、结论 总的来说,使用Greenplum进行实时推荐系统开发是一个既有趣又有挑战的任务。通过巧妙地搭建架构和精挑细选高效的算法,我们能够轻松应对海量数据的挑战,进而为用户提供贴心又个性化的推荐服务。就像是给每一片浩瀚的数据海洋架起一座智慧桥梁,让每位用户都能接收到量身定制的好内容推荐。 当然,这只是冰山一角。在未来,随着科技的进步和大家需求的不断变化,咱们的推荐系统肯定还会碰上更多意想不到的挑战,当然啦,机遇也是接踵而至、满满当当的。但是,只要我们敢于尝试,勇于创新,就一定能创造出更好的推荐系统。
2023-07-17 15:19:10
745
晚秋落叶-t
PostgreSQL
...ostgreSQL 数据复制问题深度解析与实践 1. 引言 在当今的大数据时代,数据库的稳定性、高效性和数据一致性显得尤为重要。PostgreSQL这款开源的对象关系型数据库系统,那家伙可厉害了!人家凭仗着无比强大的功能和顶呱呱的性能表现,在江湖上那是赢得了一片叫好声,圈粉无数啊!然而,在实际操作中,我们总会遇到一个挠头的大问题:怎样才能既快速又稳妥地复制数据,确保系统高度稳定、随时可恢复,还能适应分布式部署的各种需求呢?本文将深入探讨PostgreSQL的数据复制问题,并通过实例代码带您一起走进实战环节。 2. PostgreSQL 数据复制基础概念 2.1 复制类型 PostgreSQL提供了物理复制和逻辑复制两种方式。物理复制这东西,就好比有个超级认真的小秘书,它利用WAL(提前写日志)的方法,实时、同步地把数据库所有的改动“原封不动”地搬到另一个地方。而逻辑复制呢,则更像是个懂业务的翻译官,专门关注SQL这种高级命令或者一连串的操作事务,特别适合那些需要把数据分发到多个数据库,或者在传输过程中还需要对数据进行转换处理的情况。 2.2 主从复制架构 典型的PostgreSQL数据复制采用主-从架构,其中主节点负责处理写入请求并生成WAL日志,从节点则订阅并应用这些日志,从而实现数据的实时同步。 3. 物理复制实践 3.1 配置主从复制 让我们首先通过一段示例配置开启主从复制: postgresql -- 在主库上创建复制用户并赋予权限 CREATE ROLE replication_user WITH REPLICATION LOGIN ENCRYPTED PASSWORD 'your_password'; GRANT ALL PRIVILEGES ON DATABASE your_database TO replication_user; -- 查看主库的当前WAL位置 SELECT pg_current_wal_lsn(); -- 在从库上设置主库信息 RECOVERY.conf 文件内容如下: standby_mode = 'on' primary_conninfo = 'host=master_host port=5432 user=replication_user password=your_password' -- 刷新从库并启动复制进程 pg_ctl restart -D /path/to/your_slave_node_data_directory 3.2 监控与故障切换 当主库出现故障时,可以手动提升从库为新的主库。但为了实现自动化,通常会借助 Patroni 或者其它集群管理工具来管理和监控整个复制过程。 4. 逻辑复制实践 4.1 创建发布与订阅 逻辑复制需在主库上创建发布(publication),并在从库上创建订阅(subscription): postgresql -- 在主库上创建发布 CREATE PUBLICATION my_pub FOR TABLE table1, table2; -- 在从库上创建订阅 CREATE SUBSCRIPTION my_sub CONNECTION 'dbname=your_dbname host=master_host user=replication_user password=your_password' PUBLICATION my_pub; 4.2 实时同步与冲突解决 逻辑复制虽然提供更灵活的数据分发方式,但也可能引入数据冲突的问题。所以在规划逻辑复制方案的时候,咱们得充分琢磨一下冲突检测和解决的策略,就像是可以通过触发器或者应用程序自身的逻辑巧妙地进行管控那样。 5. 结论与思考 PostgreSQL的数据复制机制为我们提供了可靠的数据冗余和扩展能力,但同时也带来了一系列运维挑战,如复制延迟、数据冲突等问题。在实际操作的时候,我们得瞅准业务的特性跟需求,像挑衣服那样选出最合身的复制策略。而且呢,咱们还得像个操心的老妈子一样,时刻盯着系统的状态,随时给它调校调校,确保一切运转正常。甭管是在追求数据完美同步这条道上,还是在捣鼓系统性能提升的过程中,每一次对PostgreSQL数据复制技术的深入理解和动手实践,都像是一场充满挑战又收获满满的探险之旅。 记住,每个数据库背后都是鲜活的业务需求和海量的数据故事,我们在理解PostgreSQL数据复制的同时,也在理解着这个世界的数据流动与变迁,这正是我们热衷于此的原因所在!
2023-03-15 11:06:28
343
人生如戏
PostgreSQL
...一款功能强大、开源的关系型数据库管理系统,在全球范围内广受赞誉。不过呢,就像老话说的,“好马得配好鞍”,哪怕PostgreSQL这匹“骏马”有着超凡的性能和稳如磐石的稳定性,可一旦咱们给它配上不合适的“鞍子”,也就是配置出岔子或者系统闹点儿小情绪,那很可能就拖了它的后腿,影响性能,严重点儿还可能引发各种意想不到的问题。这篇文章咱们要接地气地聊聊,配置出岔子可能会带来的那些糟心影响,并且我还会手把手地带你瞧瞧实例代码,教你如何把配置调校得恰到好处,让这些问题通通远离咱们。 2. 配置失误对性能的影响 2.1 shared_buffers设置不合理 shared_buffers是PostgreSQL用于缓存数据的重要参数,其大小直接影响到数据库的查询性能。要是你把这数值设得过小,就等于是在让磁盘I/O忙个不停,频繁操作起来,就像个永不停歇的陀螺,会拖累整体性能,让系统跑得像只乌龟。反过来,如果你一不留神把数值调得过大,那就像是在内存里开辟了一大片空地却闲置不用,这就白白浪费了宝贵的内存资源,还会把其他系统进程挤得没地方住,人家也会闹情绪的。 postgresql -- 在postgresql.conf中调整shared_buffers值 shared_buffers = 4GB -- 假设服务器有足够内存支持此设置 2.2 work_mem不足 work_mem定义了每个SQL查询可以使用的内存量,对于复杂的排序、哈希操作等至关重要。过低的work_mem设定可能导致大量临时文件生成,进一步降低性能。 postgresql -- 调整work_mem大小 work_mem = 64MB -- 根据实际业务负载进行合理调整 3. 配置失误导致的故障案例 3.1 max_connections设置过高 max_connections参数限制了PostgreSQL同时接受的最大连接数。如果设置得过高,却没考虑服务器的实际承受能力,就像让一个普通人硬扛大铁锤,早晚得累垮。这样一来,系统资源就会被消耗殆尽,好比车票都被抢光了,新的连接请求就无法挤上这趟“网络列车”。最终,整个系统可能就要“罢工”瘫痪啦。 postgresql -- 不合理的高连接数设置示例 max_connections = 500 -- 若服务器硬件条件不足以支撑如此多的并发连接,则可能引发故障 3.2 日志设置不当造成磁盘空间耗尽 log_line_prefix、log_directory等日志相关参数设置不当,可能导致日志文件迅速增长,占用过多磁盘空间,进而引发数据库服务停止。 postgresql -- 错误的日志设置示例 log_line_prefix = '%t [%p]: ' -- 时间戳和进程ID前缀可能会使日志行变得冗长 log_directory = '/var/log/postgresql' -- 如果不加以定期清理,日志文件可能会撑满整个分区 4. 探讨与建议 面对PostgreSQL的系统配置问题,我们需要深入了解每个参数的含义以及它们在不同场景下的最佳实践。优化配置是一个持续的过程,需要结合业务特性和硬件资源来进行细致调优。 - 理解需求:首先,应了解业务特点,包括数据量大小、查询复杂度、并发访问量等因素。 - 监控分析:借助pg_stat_activity、pg_stat_bgwriter等视图监控数据库运行状态,结合如pgBadger、pg_top等工具分析性能瓶颈。 - 逐步调整:每次只更改一个参数,观察并评估效果,切忌盲目跟从网络上的推荐配置。 总结来说,PostgreSQL的强大性能背后,合理的配置是关键。要让咱们的数据库系统跑得溜又稳,像老黄牛一样可靠,给业务发展扎扎实实当好坚强后盾,那就必须把这些参数整得门儿清,调校得恰到好处才行。
2023-12-18 14:08:56
236
林中小径
转载文章
...话木马写入MySQL数据库相关文件,并通过访问特定URL触发该木马执行,进而实现对目标系统的控制。 allow_url_include , allow_url_include是PHP配置选项之一,用于决定是否允许PHP脚本通过include或require函数包含远程(HTTP/HTTPS/FTP)文件。当allow_url_include设置为On时,PHP会尝试从远程服务器获取指定路径的文件内容并当作PHP代码执行。在本文的安全实验场景中,开启此配置选项意味着攻击者可以利用远程文件包含漏洞进行攻击。 MySQL , MySQL是一个广泛使用的开源关系型数据库管理系统,可存储、管理和检索数据。在文章的实战部分,作者演示了如何利用文件包含漏洞向MySQL数据库中的表文件插入一句话木马,并通过访问生成的PHP文件来执行恶意代码,说明了在Web应用程序开发中,若对数据库操作不当,可能导致严重的安全问题。
2024-01-06 09:10:40
343
转载
Mongo
NoSQL数据库 , NoSQL(Not Only SQL)是一种非关系型数据库,它不采用传统的关系模型来存储数据,而是使用键值对、文档、列族、图形等多种数据模型进行存储。在MongoDB的语境下,其作为一种流行的NoSQL数据库,允许开发者以灵活的JSON-like文档格式存储数据,并且支持水平扩展和高可用性,尤其适合处理大量非结构化或半结构化的数据。 事务(Transaction) , 在数据库系统中,事务是一个不可分割的工作单元,它包含一系列操作,这些操作要么全部成功执行,要么全部失败回滚。在MongoDB中,从4.0版本开始支持事务功能,这意味着一组相关的数据库操作可以被封装在一个事务内,从而确保数据的一致性和完整性。事务必须满足ACID(原子性、一致性、隔离性、持久性)原则,即保证一次事务内的所有更改要么全部生效,要么全部撤销,不会出现部分生效导致的数据不一致状态。 原子性(Atomicity) , 原子性是事务处理的基本属性之一,在MongoDB中表现为一个事务中的所有操作要么全部完成,要么全部不执行。具体到文章中的电商网站示例,更新用户信息和商品库存的操作被封装在一个事务中,如果其中一个操作失败,那么整个事务将被回滚,以确保数据始终保持一致,不会处于中间状态,避免引发数据不一致的问题。
2023-12-06 15:41:34
135
时光倒流-t
Mongo
...用户并发写入场景下,数据库系统的并发控制与数据一致性问题一直是技术领域的研究热点。近期,MongoDB官方持续优化其并发处理能力,并在4.4版本中引入了“事务”功能,使得MongoDB能够支持跨文档的ACID(原子性、一致性、隔离性和持久性)事务,这对于处理复杂业务逻辑下的并发控制具有里程碑意义。 同时,随着云原生架构的发展,MongoDB Atlas作为全球分布式多云数据库服务,提供了自动分片、读写分离以及实时备份等高级功能,进一步强化了MongoDB在高并发环境下的性能表现和数据一致性保障。 值得注意的是,业界对于NoSQL数据库如何平衡扩展性与一致性的探讨从未停止。例如,CAP理论(Consistency, Availability, Partition Tolerance)为我们理解分布式系统中的权衡提供了理论基础。而诸如“最终一致性”、“因果一致性”等一致性模型的实践应用,也为解决多用户写入场景下的数据一致性问题提供了新的思路和解决方案。 此外,现代数据库设计也在借鉴传统关系型数据库的成熟经验,结合NoSQL的优势进行创新。乐观锁、悲观锁之外,还有如基于版本向量的并发控制策略在一些新型数据库系统中得到应用,这些都为应对高并发挑战提供了更多元化的方法论。 综上所述,深入理解和掌握MongoDB及其他数据库系统在并发控制方面的机制与策略,不仅有助于提升现有系统的性能与可靠性,也为未来构建更加高效、稳定的分布式应用打下了坚实的基础。
2023-06-24 13:49:52
71
人生如戏
PostgreSQL
...一款功能强大且开源的关系型数据库管理系统,一直以来都以其高度的可扩展性和可靠性赢得了全球开发者的青睐。特别是在打造那种超大型、超高稳定性的数据存储方案时,PostgreSQL的集群架构设计可真是起到了关键作用,就像搭建积木时那个不可或缺的核心支柱一样重要。这篇文会手把手地带你揭开PostgreSQL集群架构的神秘面纱,咱们一边唠嗑一边通过实实在在的代码实例,探索它在实战中的应用秘诀。 2. PostgreSQL集群基础概念 在PostgreSQL的世界里,“集群”一词并非我们通常理解的那种多节点协同工作的分布式系统概念,而是指在同一台或多台物理机器上运行多个PostgreSQL实例,共享同一套数据文件的部署方式。这种架构能够提供冗余和故障切换能力,从而实现高可用性。 然而,为了构建真正的分布式集群以应对大数据量和高并发场景,我们需要借助如PGPool-II、pg_bouncer等中间件,或者采用逻辑复制、streaming replication等内置机制来构建跨节点的PostgreSQL集群。 3. PostgreSQL集群架构实战详解 3.1 Streaming Replication(流复制) Streaming Replication是PostgreSQL提供的原生数据复制方案,它允许主从节点之间近乎实时地进行数据同步。 sql -- 在主节点上启用流复制并设置唯一标识 ALTER SYSTEM SET wal_level = 'logical'; SELECT pg_create_physical_replication_slot('my_slot'); -- 在从节点启动复制进程,并连接到主节点 sudo -u postgres pg_basebackup -h -D /var/lib/pgsql/12/data -U repuser --slot=my_slot 3.2 Logical Replication Logical Replication则提供了更灵活的数据分发机制,可以基于表级别的订阅和发布模式。 sql -- 在主节点创建发布者 CREATE PUBLICATION my_publication FOR TABLE my_table; -- 在从节点创建订阅者 CREATE SUBSCRIPTION my_subscription CONNECTION 'host= user=repuser password=mypassword' PUBLICATION my_publication; 3.3 使用中间件搭建集群 例如,使用PGPool-II可以实现负载均衡和读写分离: bash 安装并配置PGPool-II apt-get install pgpool2 vim /etc/pgpool2/pgpool.conf 配置主从节点信息以及负载均衡策略 ... backend_hostname0 = 'primary_host' backend_port0 = 5432 backend_weight0 = 1 ... 启动PGPool-II服务 systemctl start pgpool2 4. 探讨与思考 PostgreSQL集群架构的设计不仅极大地提升了系统的稳定性和可用性,也为开发者在实际业务中提供了更多的可能性。在实际操作中,咱们得根据业务的具体需求,灵活掂量各种集群方案的优先级。比如说,是不是非得保证数据强一致性?或者,咱是否需要横向扩展来应对更大规模的业务挑战?这样子去考虑就对了。另外,随着科技的不断进步,PostgreSQL这个数据库也在马不停蹄地优化自家的集群功能呢。比如说,它引入了全局事务ID、同步提交组这些酷炫的新特性,这样一来,以后在处理大规模分布式应用的时候,就更加游刃有余,相当于提前给未来铺好了一条康庄大道。 总的来说,PostgreSQL集群架构的魅力在于其灵活性和可扩展性,它像一个精密的齿轮箱,每个组件各司其职又相互协作,共同驱动着整个数据库系统高效稳健地运行。所以,在我们亲手搭建和不断优化PostgreSQL集群的过程中,每一个细微之处都值得我们去仔仔细细琢磨,每一行代码都满满地倾注了我们对数据管理这门艺术的执着追求与无比热爱。就像是在雕琢一件精美的艺术品一样,我们对每一个细节、每一段代码都充满敬畏和热情。
2023-04-03 12:12:59
248
追梦人_
Mongo
一、引言 在当今的数据驱动世界中,NoSQL数据库如MongoDB因其灵活性和高性能而备受瞩目。MongoDB是一款牛哄哄的文档型数据库,它最厉害的地方就是能灵活存储各种非关系型数据,给开发者们带来了前所未有的、超酷炫的解决方案,让他们的工作变得更轻松更高效。今天,咱们就来好好唠唠MongoDB的独门秘籍之一,那就是它如何连接数据库,以及它的异步写入到底是怎么个运作模式,让大家能有个透彻了解。 1.1 MongoDB简介 MongoDB,全名MongoDB Inc., 是一个开源的跨平台文档型数据库,其设计初衷是为了处理大量数据,特别是对于需要快速插入、读取和删除数据的应用场景。它的最大亮点就在于那个文档模型设计,就好比给数据准备了个JSON格式的房间,这样一来,甭管是半结构化的还是非结构化的数据,都能在这间房里舒舒服服地“住”下来,并且表现得格外出色。 二、连接数据库 简单易行 2.1 连接MongoDB 首先,让我们通过Node.js的官方驱动程序mongodb来连接到MongoDB服务器。这个过程其实就像这样,连接这一步呢,是同步进行的,就相当于大家一起整齐划一地行动。不过,接下来的查询操作嘛,通常会选择异步的方式来进行,这样做就像是让各个部分灵活自主地去干活,不耽误彼此的时间,从而大大提升整体的工作效率! javascript const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; const dbName = 'test'; MongoClient.connect(url, {useNewUrlParser: true}, (err, client) => { if (err) throw err; console.log("Connected to MongoDB"); const db = client.db(dbName); // ...进行数据库操作 client.close(); // 关闭连接 }); 2.2 异步与同步的区别 在上述代码中,MongoClient.connect函数会立即返回,即使连接尚未建立。这是因为它采用了异步模式,这样可以让你的代码继续执行,而不会阻塞。一旦连接成功,回调函数会被调用。这就是异步编程的魅力,它让我们的应用更加响应式。 三、异步写入 提升性能的关键 3.1 写入操作的异步性 当我们向MongoDB写入数据时,通常也采用异步方式,因为这可以避免阻塞主线程,尤其是在高并发环境下。例如,使用insertOne方法: javascript db.collection('users').insertOne({name: 'John Doe'}, (err, result) => { if (err) console.error(err); console.log(Inserted document with _id: ${result.insertedId}); }); 3.2 为什么要异步写入? 异步写入的优势在于,如果数据库正在处理其他请求,当前请求不会被阻塞,而是立即返回。这样,应用程序可以继续处理其他任务,提高了整体的吞吐量。 四、异步操作的处理与错误处理 4.1 错误处理 在异步操作中,错误通常通过回调函数传递。我们需要确保正确处理这些可能发生的异常,以便于应用程序的健壮性。 javascript db.collection('users').insertOne({name: 'Jane Doe'}, (err, result) => { if (err) { console.error('Error inserting document:', err); } else { console.log(Inserted document with _id: ${result.insertedId}); } }); 4.2 回调地狱与Promise/Async/Await 为了避免回调地狱,我们可以利用Promise、async/await等现代JavaScript特性来更优雅地处理异步操作。 javascript async function insertUser(user) { try { const result = await db.collection('users').insertOne(user); console.log(Inserted document with _id: ${result.insertedId}); } catch (error) { console.error('Error inserting document:', error); } } insertUser({name: 'Alice Smith'}); 五、结论 MongoDB的异步特性使得数据库操作更加高效,尤其在处理大规模数据和高并发场景下。你知道吗,只要咱们掌握了异步编程的窍门,灵活运用回调、Promise或者那个超好用的async/await,就能把MongoDB的大招完全发挥出来。这样一来,咱的应用程序不仅速度嗖嗖地提升,用户体验也能蹭蹭上涨,保证让用户用得爽歪歪!同时呢,异步操作这个小东西也悄悄告诉我们,在编程的过程中,咱可千万不能忽视代码的维护性和扩展性,毕竟业务需求这玩意儿是说变就变的,咱们得随时做好准备,让代码灵活适应这些变化。
2024-03-13 11:19:09
262
寂静森林_t
Linux
NoSQL数据库 , NoSQL(Not Only SQL)是一种不同于传统关系型数据库的非关系型数据库,它不依赖于固定的表结构和SQL查询语言,更适合处理大规模、半结构化或非结构化的数据。在文章中,MongoDB即为一款流行的NoSQL数据库系统,其设计目标是提供高性能、易扩展以及灵活的数据模型,以适应现代Web应用和服务的需求。 物理备份 , 物理备份是指直接复制数据库相关的所有文件到其他存储位置的过程,这些文件通常包含了数据库的所有数据和元数据信息。在Linux环境下对MongoDB进行物理备份时,用户会通过命令行工具复制MongoDB数据存储路径下的所有文件至备份目录,从而实现整个数据库在某一时间点的完整状态备份。 逻辑备份 , 逻辑备份则是将数据库中的数据按照特定格式导出成一系列可以理解的文件(如JSON或bson格式),这些文件能够反映出数据库的内容,但不包含底层存储的具体实现细节。在本文中,mongodump工具被用来执行MongoDB的逻辑备份,它可以读取数据库的内容并生成可导入回MongoDB实例的bson文件集合,便于迁移、归档或者恢复数据。 MongoDB Atlas , MongoDB Atlas 是MongoDB官方提供的完全托管型云数据库服务,用户无需关注底层基础设施管理,即可享受到自动化的集群部署、监控、备份与恢复等高级功能。在文中提到,MongoDB Atlas内置了自动备份功能,允许用户自定义备份策略,系统会按照设定的时间周期自动完成数据库的备份任务,极大地简化了数据库管理和维护工作。
2023-06-14 17:58:12
452
寂静森林_
ClickHouse
无法处理跨数据库或表的复杂查询和操作?别急,我们来聊聊ClickHouse! 1. 初识ClickHouse 它到底是什么? 大家好啊!今天咱们来聊一聊ClickHouse这个神奇的东西。要是你对数据分析或者存一堆数据的事儿挺感兴趣的,那肯定听过这个词啦!ClickHouse是一个开源的列式数据库管理系统,专为超快的实时分析而设计。它的速度非常惊人,可以轻松应对TB甚至PB级别的数据量。 但是呢,就像所有工具都有自己的特点一样,ClickHouse也有它的局限性。其实呢,它的一个小短板就是,在面对跨数据库或者跨表的那种复杂查询时,有时候会有点招架不住,感觉有点使不上劲儿。这可不是说它不好,而是我们需要了解它的能力边界在哪里。 让我先举个例子吧。假设你有两个表A和B,分别存储了不同的业务数据。如果你打算在一个查询里同时用上这两个表的数据,然后搞点复杂的操作(比如说JOIN那种),你可能会发现,ClickHouse 并不像某些关系型数据库那么“丝滑”,有时候它可能会让你觉得有点费劲。这是为什么呢?让我们一起来探究一下。 --- 2. ClickHouse的工作原理揭秘 首先,我们要明白ClickHouse是怎么工作的。它用的是列式存储,简单说就是把一整列的数据像叠积木一样整整齐齐地堆在一起,而不是东一个西一个乱放。这种设计特别适合处理海量数据的情况,比如你只需要拿其中一小块儿,完全不用像行式存储那样一股脑儿把整条记录全读进来,多浪费时间啊! 但是这也带来了一个问题——当你想要执行跨表的操作时,事情就变得复杂了。为什么呢?因为ClickHouse的设计初衷并不是为了支持复杂的JOIN操作。它的查询引擎在处理简单的事儿,比如筛选一下数据或者做个汇总啥的,那是一把好手。但要是涉及到多张表格之间的复杂关系,它就有点转不过弯来了,感觉像是被绕晕了的小朋友。 举个例子来说,如果你有一张用户表User和一张订单表Order,你想找出所有购买了特定商品的用户信息,这听起来很简单对不对?但在ClickHouse里,这样的JOIN操作可能会导致性能下降,甚至直接失败。 sql SELECT u.id, o.order_id FROM User AS u JOIN Order AS o ON u.id = o.user_id; 这段SQL看起来很正常,但运行起来可能会让你抓狂。所以接下来,我们就来看看如何在这种情况下找到解决方案。 --- 3. 面临的挑战与解决之道 既然我们知道ClickHouse不太擅长处理复杂的跨表查询,那么我们应该怎么办呢?其实方法还是有很多的,只是需要我们稍微动点脑筋罢了。 方法一:数据预处理 最直接的办法就是提前做好准备。你可以先把两张表格的数据合到一块儿,变成一个新表格,之后就在这个新表格里随便查啥都行。虽然听起来有点麻烦,但实际上这种方法非常有效。 比如说,我们可以创建一个新的视图,将两张表的内容联合起来: sql CREATE VIEW CombinedData AS SELECT u.id AS user_id, u.name AS username, o.order_id FROM User AS u JOIN Order AS o ON u.id = o.user_id; 这样,当你需要查询相关信息时,就可以直接从这个视图中获取,而不需要每次都做JOIN操作。 方法二:使用Materialized Views 另一种思路是利用Materialized Views(物化视图)。简单说吧,物化视图就像是提前算好答案的一张表格。一旦下面的数据改了,这张表格也会跟着自动更新,就跟变魔术似的!这种方式特别适合于那些经常被查询的数据模式。 例如,如果我们知道某个查询会频繁出现,就可以事先定义一个物化视图来加速: sql CREATE MATERIALIZED VIEW AggregatedOrders TO AggregatedTable AS SELECT user_id, COUNT(order_id) AS order_count FROM Orders GROUP BY user_id; 通过这种方式,每次查询时都不需要重新计算这些统计数据,从而大大提高了效率。 --- 4. 实战演练 动手试试看! 好了,理论讲得差不多了,现在该轮到实战环节啦!我来给大家展示几个具体的例子,看看如何在实际场景中应用上述提到的方法。 示例一:合并数据到单表 假设我们有两个表:Sales 和 Customers,它们分别记录了销售记录和客户信息。现在我们想找出每个客户的总销售额。 sql -- 创建视图 CREATE VIEW SalesByCustomer AS SELECT c.customer_id, c.name, SUM(s.amount) AS total_sales FROM Customers AS c JOIN Sales AS s ON c.customer_id = s.customer_id GROUP BY c.customer_id, c.name; -- 查询结果 SELECT FROM SalesByCustomer WHERE total_sales > 1000; 示例二:使用物化视图优化查询 继续上面的例子,如果我们发现SalesByCustomer视图被频繁访问,那么就可以进一步优化,将其转换为物化视图: sql -- 创建物化视图 CREATE MATERIALIZED VIEW SalesSummary ENGINE = MergeTree() ORDER BY customer_id AS SELECT customer_id, name, SUM(amount) AS total_sales FROM Sales JOIN Customers USING (customer_id) GROUP BY customer_id, name; -- 查询物化视图 SELECT FROM SalesSummary WHERE total_sales > 1000; 可以看到,相比之前的视图方式,物化视图不仅减少了重复计算,还提供了更好的性能表现。 --- 5. 总结与展望 总之,尽管ClickHouse在处理跨数据库或表的复杂查询方面存在一定的限制,但这并不意味着它无法胜任大型项目的需求。其实啊,只要咱们好好琢磨一下怎么安排和设计,这些问题根本就不用担心啦,还能把ClickHouse的好处发挥得足足的! 最后,我想说的是,技术本身并没有绝对的好坏之分,关键在于我们如何运用它。希望今天的分享能帮助你在使用ClickHouse的过程中更加得心应手。如果还有任何疑问或者想法,欢迎随时交流讨论哦! 加油,我们一起探索更多可能性吧!
2025-04-24 16:01:03
23
秋水共长天一色
MySQL
...越来越多的企业选择将数据库迁移到云端,这一趋势不仅改变了传统IT基础设施的布局,也对数据库的安全性和性能提出了新的挑战。以亚马逊AWS和微软Azure为代表的云服务商纷纷推出专用的托管数据库服务,如Amazon RDS和Azure Database for MySQL。这些服务不仅简化了数据库管理流程,还提供了自动备份、高可用性以及更灵活的扩展能力,帮助企业降低了运维成本。 然而,在享受便利的同时,企业也面临数据隐私保护的压力。例如,欧盟《通用数据保护条例》(GDPR)要求企业在存储和处理个人数据时必须严格遵守相关规定,否则将面临巨额罚款。因此,企业在选择云数据库供应商时,不仅要考虑技术层面的因素,还需关注其合规性与安全性措施。以Google Cloud为例,他们最近宣布升级其Cloud SQL服务,增加了更多加密选项以及更强的身份验证机制,以应对日益严峻的网络安全威胁。 此外,开源数据库社区也在快速发展。PostgreSQL作为功能强大的关系型数据库管理系统,近年来因其丰富的插件生态和高度可定制性而受到广泛关注。据统计,全球范围内PostgreSQL的使用率在过去两年内增长了约40%,成为仅次于MySQL的第二大最受欢迎的关系型数据库。这表明,无论是商业产品还是开源项目,都在不断演进以满足现代企业的多样化需求。 对于普通开发者而言,掌握最新的数据库技术和最佳实践至关重要。例如,了解如何高效地进行数据迁移、优化查询性能以及实施灾难恢复策略,都是确保业务连续性的关键技能。同时,随着人工智能技术的进步,智能化数据库管理工具逐渐兴起,它们能够自动识别潜在问题并提供解决方案,极大提升了开发效率。 总之,数据库领域正经历着前所未有的变革,无论是云转型、法规遵从还是技术创新,都值得每一位从业者持续关注和学习。未来,数据库将更加智能、安全且易于使用,为企业创造更大的价值。
2025-03-24 15:46:41
78
笑傲江湖
SpringBoot
...Boot与Druid集成场景? 1. 引子 我的困惑之旅 作为一个刚入行不久的Java开发工程师,我最近在负责一个基于Spring Boot的项目。这个项目需要与Oracle数据库交互,而我选用了Druid作为数据源管理工具。事情本来挺顺的,大家都觉得没啥问题,结果有一天,我们的系统突然蹦出个消息,说啥“查询超时”!就那么一下,气氛瞬间紧张了,感觉空气都凝固了似的。 当时我整个人都懵了——这到底是什么情况?是Oracle的问题吗?还是Spring Boot的锅?或者是我对Druid的理解还不够深入?带着这些疑问,我开始了一段探索之旅。今天,我想把这段经历分享给大家,希望能帮助那些和我一样遇到类似问题的朋友。 --- 2. 什么是“查询超时”? 简单来说,“查询超时”就是你的SQL语句执行的时间超过了设定的最大允许时间,导致系统直接抛出异常。哎呀,这种情况在实际开发里真的挺常见的,特别是那种高并发的场景。你要是数据库连接池没配好,那问题就容易冒出来了,简直防不胜防! 对于我来说,这个问题尤其令人头疼,因为我们的项目依赖于Oracle数据库,而Oracle本身就是一个功能强大的关系型数据库,但同时也有一些“坑”。比如说啊,它的默认查询超时时间可能设得有点短,要是咱们不改一下这个设置,那查询的时候就容易卡壳儿,最后连结果都拿不到。 --- 3. Spring Boot与Druid集成的基本配置 首先,让我们回顾一下如何在Spring Boot项目中集成Druid。这是一个非常基础的操作,但也是解决问题的第一步。 3.1 添加依赖 在pom.xml文件中添加Druid的相关依赖: xml com.alibaba druid-spring-boot-starter 1.2.8 3.2 配置数据源 接着,在application.yml文件中配置Druid的数据源信息: yaml spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: oracle.jdbc.driver.OracleDriver url: jdbc:oracle:thin:@localhost:1521:orcl username: your_username password: your_password druid: initial-size: 5 max-active: 20 min-idle: 5 max-wait: 60000 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 validation-query: SELECT 1 FROM DUAL test-while-idle: true test-on-borrow: false test-on-return: false 这段配置看似简单,但实际上每一项参数都需要仔细斟酌。比如说啊,“max-wait”这个参数呢,就是说咱们能等连接连上的最长时间,单位是毫秒,相当于给它设了个“最长等待时间”;然后还有个“validation-query”,这个名字听起来就挺专业的,它的作用就是检查连接是不是还正常好用;最后那个“test-while-idle”,它就像是个“巡逻兵”,负责判断要不要在连接空闲的时候去检测一下这条连接还能不能用。 --- 4. 查询超时问题的初步排查 当我第一次遇到查询超时问题时,我的第一反应是:是不是Oracle那边的SQL语句太慢了?于是,我开始检查SQL语句的性能。 4.1 检查SQL语句 我用PL/SQL Developer连接到Oracle数据库,运行了一下报错的SQL语句。结果显示,这条SQL语句确实需要花费较长时间才能完成。但问题是,为什么Spring Boot会直接抛出超时异常呢? 这时,我才意识到,可能是Druid的数据源配置有问题。于是我翻阅了Druid的官方文档,发现了一个关键点:Druid默认的查询超时时间为10秒。 4.2 修改Druid的查询超时时间 为了延长查询超时时间,我在application.yml中加入了以下配置: yaml spring: datasource: druid: query-timeout: 30000 这里的query-timeout参数就是用来设置查询超时时间的,单位是毫秒。经过这次调整后,我发现查询超时的问题暂时得到了缓解。 --- 5. 进一步优化 结合Oracle的设置 虽然Druid的配置解决了部分问题,但我仍然觉得不够完美。于是,我又转向了Oracle数据库本身的设置。 5.1 设置Oracle的查询超时 在Oracle中,可以通过设置statement_timeout参数来控制查询超时时间。这个参数可以在会话级别或全局级别进行设置。 例如,在Spring Boot项目中,我们可以通过JDBC连接字符串传递这个参数: yaml spring: datasource: url: jdbc:oracle:thin:@localhost:1521:orcl?oracle.net.CONNECT_TIMEOUT=30000&oracle.jdbc.ReadTimeout=30000 这里的CONNECT_TIMEOUT和ReadTimeout分别表示连接超时时间和读取超时时间。通过这种方式,我们可以进一步提高系统的容错能力。 --- 6. 我的感悟与总结 经过这次折腾,我对Spring Boot与Druid的集成有了更深的理解。说实话,好多技术难题没那么玄乎,就是看着吓人而已。只要你肯静下心来琢磨琢磨,肯定能想出个辙来! 在这里,我也想给新手朋友们一些建议: 1. 多看官方文档 无论是Spring Boot还是Druid,它们的官方文档都非常详细,很多时候答案就在那里。 2. 学会调试 遇到问题时,不要急于求解,先用调试工具一步步分析问题所在。 3. 保持耐心 技术问题往往需要反复尝试,不要轻易放弃。 最后,我想说的是,编程之路充满了挑战,但也正因为如此才显得有趣。希望大家都能在这个过程中找到属于自己的乐趣! --- 好了,这篇文章就到这里啦!如果你也有类似的经历或想法,欢迎在评论区跟我交流哦!
2025-04-21 15:34:10
39
冬日暖阳_
MySQL
...全球范围内云计算和大数据技术的快速发展,数据库运维领域也迎来了新的挑战与机遇。以MySQL为代表的开源关系型数据库,在企业级应用中依然占据主导地位,但伴随其广泛使用的是愈发复杂的系统架构和更高的性能需求。就在上周,某知名电商公司在其大规模分布式数据库集群中遭遇了类似的问题——由于未及时调整文件描述符限制,导致核心业务系统在高并发访问时频繁出现“Too many open files”的错误,严重影响用户体验。这一事件引发了业内对于数据库资源管理的关注。 事实上,此类问题并非孤立存在。根据权威机构发布的最新报告显示,近年来因数据库配置不当而导致的服务中断比例逐年上升。特别是在互联网行业,随着微服务架构的普及,单个应用程序可能依赖数十甚至上百个数据库实例,这对数据库的稳定性提出了更高要求。此外,随着人工智能算法模型训练需求的增长,大模型的数据存储与计算任务也给传统数据库带来了前所未有的压力。 针对上述趋势,国内外多家科技公司已经开始探索更加智能化的数据库运维解决方案。例如,谷歌推出的Cloud SQL自动扩展功能可以根据实时流量动态调整资源分配,从而有效缓解类似问题的发生;阿里云则推出了PolarDB-X产品线,专门针对超高并发场景进行了优化设计。这些创新举措表明,未来数据库运维将朝着自动化、智能化方向发展。 与此同时,开源社区也在积极贡献力量。Linux内核开发者近日宣布,将在即将发布的5.18版本中引入一项名为“FD-PIN”的新特性,该特性能够显著提高文件描述符管理效率,为数据库等高性能应用场景提供更多可能性。这无疑为解决“Too many open files”这类经典问题提供了全新思路。 综上所述,无论是从技术演进还是实际案例来看,如何高效管理数据库资源已成为当下亟待解决的重要课题。作为从业者,我们需要紧跟时代步伐,不断学习新技术,同时注重实践经验积累,唯有如此才能更好地应对未来的挑战。
2025-04-17 16:17:44
109
山涧溪流_
转载文章
...视化操作,二是后台的数据库管理。网管对前台的管理和维护工作包括保障网络链路通畅、处理MIS终端的突发事件以及对操作员的管理、培训等,这是网管们日常做得最多、最辛苦的功课;然而MIS系统架构中同等重要的针对数据库的管理、维护和优化工作,现实中似乎并没有得到网管朋友的足够重视,看起来这都是程序员的事,事实上,一个网管如果能在MIS设计期间就数据表的规范化、表索引优化、容量设计、事务处理等诸多方面与程序员进行卓有成效的沟通和协作,那么日常的前台管理工作将会变得大为轻松,因为在某种意义上,数据库管理系统就相当于操作系统,在系统中占有同样重要的位置。 这正是SQL SERVER等数据库管理系统和dBASEX、ACCESS等数据库文件系统的本质区别,所以,对数据库管理系统操作能力的强弱在某种程度上也折射出了网管的水平——个人认为,称得上优秀的Admin,至少应该是一个称职的DBA(数据库管理员)。 下面以SQL SERVER(下称 SQLS)为例,将数据库管理中难于理解的“索引原理”问题给各位朋友作一个深入浅出的介绍。其他的数据库管理系统如Oracle、Sybase等,朋友们可以融会贯通,举一反三。 一、数据表的基本结构 建立数据库的目的是管理大量数据,而建立索引的目的就是提高数据检索效率,改善数据库工作性能,提高数据访问速度。对于索引,我们要知其然,更要知其所以然,关键在于认识索引的工作原理,才能更好的管理索引。 为认识索引工作原理,首先有必要对数据表的基本结构作一次全面的复习。 SQLS当一个新表被创建之时,系统将在磁盘中分配一段以8K为单位的连续空间,当字段的值从内存写入磁盘时,就在这一既定空间随机保存,当一个8K用完的时候,SQLS指针会自动分配一个8K的空间。这里,每个8K空间被称为一个数据页(Page),又名页面或数据页面,并分配从0-7的页号,每个文件的第0页记录引导信息,叫文件头(File header);每8个数据页(64K)的组合形成扩展区(Extent),称为扩展。全部数据页的组合形成堆(Heap)。 SQLS规定行不能跨越数据页,所以,每行记录的最大数据量只能为8K。这就是char和varchar这两种字符串类型容量要限制在8K以内的原因,存储超过8K的数据应使用text类型,实际上,text类型的字段值不能直接录入和保存,它只是存储一个指针,指向由若干8K的文本数据页所组成的扩展区,真正的数据正是放在这些数据页中。 页面有空间页面和数据页面之分。 当一个扩展区的8个数据页中既包含了空间页面又包括了数据或索引页面时,称为混合扩展(Mixed Extent),每张表都以混合扩展开始;反之,称为一致扩展(Uniform Extent),专门保存数据及索引信息。 表被创建之时,SQLS在混合扩展中为其分配至少一个数据页面,随着数据量的增长,SQLS可即时在混合扩展中分配出7个页面,当数据超过8个页面时,则从一致扩展中分配数据页面。 空间页面专门负责数据空间的分配和管理,包括:PFS页面(Page free space):记录一个页面是否已分配、位于混合扩展还是一致扩展以及页面上还有多少可用空间等信息;GAM页面(Global allocation map)和SGAM页面(Secodary global allocation map):用来记录空闲的扩展或含有空闲页面的混合扩展的位置。SQLS综合利用这三种类型的页面文件在必要时为数据表创建新空间; 数据页或索引页则专门保存数据及索引信息,SQLS使用4种类型的数据页面来管理表或索引:它们是IAM页、数据页、文本/图像页和索引页。 在WINDOWS中,我们对文件执行的每一步操作,在磁盘上的物理位置只有系统(system)才知道;SQL SERVER沿袭了这种工作方式,在插入数据的过程中,不但每个字段值在数据页面中的保存位置是随机的,而且每个数据页面在“堆”中的排列位置也只有系统(system)才知道。 这是为什么呢?众所周知,OS之所以能管理DISK,是因为在系统启动时首先加载了文件分配表:FAT(File Allocation Table),正是由它管理文件系统并记录对文件的一切操作,系统才得以正常运行;同理,作为管理系统级的SQL SERVER,也有这样一张类似FAT的表存在,它就是索引分布映像页:IAM(Index Allocation Map)。 IAM的存在,使SQLS对数据表的物理管理有了可能。 IAM页从混合扩展中分配,记录了8个初始页面的位置和该扩展区的位置,每个IAM页面能管理512,000个数据页面,如果数据量太大,SQLS也可以增加更多的IAM页,可以位于文件的任何位置。第一个IAM页被称为FirstIAM,其中记录了以后的IAM页的位置。 数据页和文本/图像页互反,前者保存非文本/图像类型的数据,因为它们都不超过8K的容量,后者则只保存超过8K容量的文本或图像类型数据。而索引页顾名思义,保存的是与索引结构相关的数据信息。了解页面的问题有助我们下一步准确理解SQLS维护索引的方式,如页拆分、填充因子等。 二、索引的基本概念 索引是一种特殊类型的数据库对象,它与表有着密切的联系。 索引是为检索而存在的。如一些书籍的末尾就专门附有索引,指明了某个关键字在正文中的出现的页码位置,方便我们查找,但大多数的书籍只有目录,目录不是索引,只是书中内容的排序,并不提供真正的检索功能。可见建立索引要单独占用空间;索引也并不是必须要建立的,它们只是为更好、更快的检索和定位关键字而存在。 再进一步说,我们要在图书馆中查阅图书,该怎么办呢?图书馆的前台有很多叫做索引卡片柜的小柜子,里面分了若干的类别供我们检索图书,比如你可以用书名的笔画顺序或者拼音顺序作为查找的依据,你还可以从作者名的笔画顺序或拼音顺序去查询想要的图书,反正有许多检索方式,但有一点很明白,书库中的书并没有按照这些卡片柜中的顺序排列——虽然理论上可以这样做,事实上,所有图书的脊背上都人工的粘贴了一个特定的编号①,它们是以这个顺序在排列。索引卡片中并没有指明这本书摆放在书库中的第几个书架的第几本,仅仅指明了这个特定的编号。管理员则根据这一编号将请求的图书返回到读者手中。这是很形象的例子,以下的讲解将会反复用到它。 SQLS在安装完成之后,安装程序会自动创建master、model、tempdb等几个特殊的系统数据库,其中master是SQLS的主数据库,用于保存和管理其它系统数据库、用户数据库以及SQLS的系统信息,它在SQLS中的地位与WINDOWS下的注册表相当。 master中有一个名为sysindexes的系统表,专门管理索引。SQLS查询数据表的操作都必须用到它,毫无疑义,它是本文主角之一。 查看一张表的索引属性,可以在查询分析器中使用以下命令:select from sysindexes where id=object_id(‘tablename’) ;而要查看表的索引所占空间的大小,可以使用系统存储过程命令:sp_spaceused tablename,其中参数tablename为被索引的表名。 三、平衡树 如果你通过书后的索引知道了一个关键字所在的页码,你有可能通过随机的翻寻,最终到达正确的页码。但更科学更快捷的方法是:首先把书翻到大概二分之一的位置,如果要找的页码比该页的页码小,就把书向前翻到四分之一处,否则,就把书向后翻到四分之三的地方,依此类推,把书页续分成更小的部分,直至正确的页码。这叫“两分法”,微软在官方教程MOC里另有一种说法:叫B树(B-Tree,Balance Tree),即平衡树。 一个表索引由若干页面组成,这些页面构成了一个树形结构。B树由“根”(root)开始,称为根级节点,它通过指向另外两个页,把一个表的记录从逻辑上分成两个部分:“枝”—--非叶级节点(Non-Leaf Level);而非叶级节点又分别指向更小的部分:“叶”——叶级节点(Leaf Level)。根节点、非叶级节点和叶级节点都位于索引页中,统称为索引节点,属于索引页的范筹。这些“枝”、“叶”最终指向了具体的数据页(Page)。在根级节点和叶级节点之间的叶又叫数据中间页。 “根”(root)对应了sysindexes表的Root字段,其中记载了非叶级节点的物理位置(即指针);非叶级节点位于根节点和叶节点之间,记载了指向叶级节点的指针;而叶级节点则最终指向数据页。这就是“平衡树”。 四、聚集索引和非聚集索引 从形式上而言,索引分为聚集索引(Clustered Indexes)和非聚集索引(NonClustered Indexes)。 聚集索引相当于书籍脊背上那个特定的编号。如果对一张表建立了聚集索引,其索引页中就包含着建立索引的列的值(下称索引键值),那么表中的记录将按照该索引键值进行排序。比如,我们如果在“姓名”这一字段上建立了聚集索引,则表中的记录将按照姓名进行排列;如果建立了聚集索引的列是数值类型的,那么记录将按照该键值的数值大小来进行排列。 非聚集索引用于指定数据的逻辑顺序,也就是说,表中的数据并没有按照索引键值指定的顺序排列,而仍然按照插入记录时的顺序存放。其索引页中包含着索引键值和它所指向该行记录在数据页中的物理位置,叫做行定位符(RID:Row ID)。好似书后面的的索引表,索引表中的顺序与实际的页码顺序也是不一致的。而且一本书也许有多个索引。比如主题索引和作者索引。 SQL Server在默认的情况下建立的索引是非聚集索引,由于非聚集索引不对表中的数据进行重组,而只是存储索引键值并用一个指针指向数据所在的页面。一个表如果没有聚集索引时,理论上可以建立249个非聚集索引。每个非聚集索引提供访问数据的不同排序顺序。 五、数据是怎样被访问的 若能真正理解了以上索引的基础知识,那么再回头来看索引的工作原理就简单和轻松多了。 (一)SQLS怎样访问没有建立任何索引数据表: Heap译成汉语叫做“堆”,其本义暗含杂乱无章、无序的意思,前面提到数据值被写进数据页时,由于每一行记录之间并没地有特定的排列顺序,所以行与行的顺序就是随机无序的,当然表中的数据页也就是无序的了,而表中所有数据页就形成了“堆”,可以说,一张没有索引的数据表,就像一个只有书柜而没有索引卡片柜的图书馆,书库里面塞满了一堆乱七八糟的图书。当读者对管理员提交查询请求后,管理员就一头钻进书库,对照查找内容从头开始一架一柜的逐本查找,运气好的话,在第一个书架的第一本书就找到了,运气不好的话,要到最后一个书架的最后一本书才找到。 SQLS在接到查询请求的时候,首先会分析sysindexes表中一个叫做索引标志符(INDID: Index ID)的字段的值,如果该值为0,表示这是一张数据表而不是索引表,SQLS就会使用sysindexes表的另一个字段——也就是在前面提到过的FirstIAM值中找到该表的IAM页链——也就是所有数据页集合。 这就是对一个没有建立索引的数据表进行数据查找的方式,是不是很没效率?对于没有索引的表,对于一“堆”这样的记录,SQLS也只能这样做,而且更没劲的是,即使在第一行就找到了被查询的记录,SQLS仍然要从头到尾的将表扫描一次。这种查询称为“遍历”,又叫“表扫描”。 可见没有建立索引的数据表照样可以运行,不过这种方法对于小规模的表来说没有什么太大的问题,但要查询海量的数据效率就太低了。 (二)SQLS怎样访问建立了非聚集索引的数据表: 如前所述,非聚集索引可以建多个,具有B树结构,其叶级节点不包含数据页,只包含索引行。假定一个表中只有非聚集索引,则每个索引行包含了非聚集索引键值以及行定位符(ROW ID,RID),他们指向具有该键值的数据行。每一个RID由文件ID、页编号和在页中行的编号组成。 当INDID的值在2-250之间时,意味着表中存在非聚集索引页。此时,SQLS调用ROOT字段的值指向非聚集索引B树的ROOT,在其中查找与被查询最相近的值,根据这个值找到在非叶级节点中的页号,然后顺藤摸瓜,在叶级节点相应的页面中找到该值的RID,最后根据这个RID在Heap中定位所在的页和行并返回到查询端。 例如:假定在Lastname上建立了非聚集索引,则执行Select From Member Where Lastname=’Ota’时,查询过程是:①SQLS查询INDID值为2;②立即从根出发,在非叶级节点中定位最接近Ota的值“Martin”,并查到其位于叶级页面的第61页;③仅在叶级页面的第61页的Martin下搜寻Ota的RID,其RID显示为N∶706∶4,表示Lastname字段中名为Ota的记录位于堆的第707页的第4行,N表示文件的ID值,与数据无关;④根据上述信息,SQLS立马在堆的第 707页第4行将该记录“揪”出来并显示于前台(客户端)。视表的数据量大小,整个查询过程费时从百分之几毫秒到数毫秒不等。 在谈到索引基本概念的时候,我们就提到了这种方式: 图书馆的前台有很多索引卡片柜,里面分了若干的类别,诸如按照书名笔画或拼音顺序、作者笔画或拼音顺序等等,但不同之处有二:① 索引卡片上记录了每本书摆放的具体位置——位于某柜某架的第几本——而不是“特殊编号”;② 书脊上并没有那个“特殊编号”。管理员在索引柜中查到所需图书的具体位置(RID)后,根据RID直接在书库中的具体位置将书提出来。 显然,这种查询方式效率很高,但资源占用极大,因为书库中书的位置随时在发生变化,必然要求管理员花费额外的精力和时间随时做好索引更新。 (三)SQLS怎样访问建立了聚集索引的数据表: 在聚集索引中,数据所在的数据页是叶级,索引数据所在的索引页是非叶级。 查询原理和上述对非聚集索引的查询相似,但由于记录是按照聚集索引中索引键值进行排序,换句话说,聚集索引的索引键值也就是具体的数据页。 这就好比书库中的书就是按照书名的拼音在排序,而且也只按照这一种排序方式建立相应的索引卡片,于是查询起来要比上述只建立非聚集索引的方式要简单得多。仍以上面的查询为例: 假定在Lastname字段上建立了聚集索引,则执行Select From Member Where Lastname=’Ota’时,查询过程是:①SQLS查询INDID值为1,这是在系统中只建立了聚集索引的标志;②立即从根出发,在非叶级节点中定位最接近Ota的值“Martin”,并查到其位于叶级页面的第120页;③在位于叶级页面第120页的Martin下搜寻到Ota条目,而这一条目已是数据记录本身;④将该记录返回客户端。 这一次的效率比第二种方法更高,以致于看起来更美,然而它最大的优点也恰好是它最大的缺点——由于同一张表中同时只能按照一种顺序排列,所以在任何一种数据表中的聚集索引只能建立一个;并且建立聚集索引需要至少相当于源表120%的附加空间,以存放源表的副本和索引中间页! 难道鱼和熊掌就不能兼顾了吗?办法是有的。 (四)SQLS怎样访问既有聚集索引、又有非聚集索引的数据表: 如果我们在建立非聚集索引之前先建立了聚集索引的话,那么非聚集索引就可以使用聚集索引的关键字进行检索,就像在图书馆中,前台卡片柜中的可以有不同类别的图书索引卡,然而每张卡片上都载明了那个特殊编号——并不是书籍存放的具体位置。这样在最大程度上既照顾了数据检索的快捷性,又使索引的日常维护变得更加可行,这是最为科学的检索方法。 也就是说,在只建立了非聚集索引的情况下,每个叶级节点指明了记录的行定位符(RID);而在既有聚集索引又有非聚集索引的情况下,每个叶级节点所指向的是该聚集索引的索引键值,即数据记录本身。 假设聚集索引建立在Lastname上,而非聚集索引建立在Firstname上,当执行Select From Member Where Firstname=’Mike’时,查询过程是:①SQLS查询INDID值为2;②立即从根出发,在Firstname的非聚集索引的非叶级节点中定位最接近Mike的值“Jose”条目;③从Jose条目下的叶级页面中查到Mike逻辑位置——不是RID而是聚集索引的指针;④根据这一指针所指示位置,直接进入位于Lastname的聚集索引中的叶级页面中到达Mike数据记录本身;⑤将该记录返回客户端。 这就完全和我们在“索引的基本概念”中讲到的现实场景完全一样了,当数据发生更新的时候,SQLS只负责对聚集索引的健值驾以维护,而不必考虑非聚集索引,只要我们在ID类的字段上建立聚集索引,而在其它经常需要查询的字段上建立非聚集索引,通过这种科学的、有针对性的在一张表上分别建立聚集索引和非聚集索引的方法,我们既享受了索引带来的灵活与快捷,又相对规避了维护索引所导致的大量的额外资源消耗。 六、索引的优点和不足 索引有一些先天不足:1:建立索引,系统要占用大约为表的1.2倍的硬盘和内存空间来保存索引。2:更新数据的时候,系统必须要有额外的时间来同时对索引进行更新,以维持数据和索引的一致性——这就如同图书馆要有专门的位置来摆放索引柜,并且每当库存图书发生变化时都需要有人将索引卡片重整以保持索引与库存的一致。 当然建立索引的优点也是显而易见的:在海量数据的情况下,如果合理的建立了索引,则会大大加强SQLS执行查询、对结果进行排序、分组的操作效率。 实践表明,不恰当的索引不但于事无补,反而会降低系统性能。因为大量的索引在进行插入、修改和删除操作时比没有索引花费更多的系统时间。比如在如下字段建立索引应该是不恰当的:1、很少或从不引用的字段;2、逻辑型的字段,如男或女(是或否)等。 综上所述,提高查询效率是以消耗一定的系统资源为代价的,索引不能盲目的建立,必须要有统筹的规划,一定要在“加快查询速度”与“降低修改速度”之间做好平衡,有得必有失,此消则彼长。这是考验一个DBA是否优秀的很重要的指标。 至此,我们一直在说SQLS在维护索引时要消耗系统资源,那么SQLS维护索引时究竟消耗了什么资源?会产生哪些问题?究竟应该才能优化字段的索引? 在上篇中,我们就索引的基本概念和数据查询原理作了详细阐述,知道了建立索引时一定要在“加快查询速度”与“降低修改速度”之间做好平衡,有得必有失,此消则彼长。那么,SQLS维护索引时究竟怎样消耗资源?应该从哪些方面对索引进行管理与优化?以下就从七个方面来回答这些问题。 一、页分裂 微软MOC教导我们:当一个数据页达到了8K容量,如果此时发生插入或更新数据的操作,将导致页的分裂(又名页拆分): 1、有聚集索引的情况下:聚集索引将被插入和更新的行指向特定的页,该页由聚集索引关键字决定; 2、只有堆的情况下:只要有空间就可以插入新的行,但是如果我们对行数据的更新需要更多的空间,以致大于了当前页的可用空间,行就被移到新的页中,并且在原位置留下一个转发指针,指向被移动的新行,如果具有转发指针的行又被移动了,那么原来的指针将重新指向新的位置; 3、如果堆中有非聚集索引,那么尽管插入和更新操作在堆中不会发生页分裂,但是在非聚集索引上仍然产生页分裂。 无论有无索引,大约一半的数据将保留在老页面,而另一半将放入新页面,并且新页面可能被分配到任何可用的页。所以,频繁页分裂,后果很严重,将使物理表产生大量数据碎片,导致直接造成I/O效率的急剧下降,最后,停止SQLS的运行并重建索引将是我们的唯一选择! 二、填充因子 然而在“混沌之初”,就可以在一定程度上避免不愉快出现:在创建索引时,可以为这个索引指定一个填充因子,以便在索引的每个叶级页面上保留一定百分比的空间,将来数据可以进行扩充和减少页分裂。填充因子是从0到100的百分比数值,设为100时表示将数据页填满。只有当不会对数据进行更改时(例如只读表中)才用此设置。值越小则数据页上的空闲空间越大,这样可以减少在索引增长过程中进行页分裂的需要,但这一操作需要占用更多的硬盘空间。 填充因子只在创建索引时执行,索引创建以后,当表中进行数据的添加、删除或更新时,是不会保持填充因子的,如果想在数据页上保持额外的空间,则有悖于使用填充因子的本意,因为随着数据的输入,SQLS必须在每个页上进行页拆分,以保持填充因子指定的空闲空间。因此,只有在表中的数据进行了较大的变动,才可以填充数据页的空闲空间。这时,可以从容的重建索引,重新指定填充因子,重新分布数据。 反之,填充因子指定不当,就会降低数据库的读取性能,其降低量与填充因子设置值成反比。例如,当填充因子的值为50时,数据库的读取性能会降低两倍!所以,只有在表中根据现有数据创建新索引,并且可以预见将来会对这些数据进行哪些更改时,设置填充因子才有意义。 三、两道数学题 假定数据库设计没有问题,那么是否象上篇中分析的那样,当你建立了众多的索引,在查询工作中SQLS就只能按照“最高指示”用索引处理每一个提交的查询呢?答案是否定的! 上篇“数据是怎样被访问的”章节中提到的四种索引方案只是一种静态的、标准的和理论上的分析比较,实际上,将在外,军令有所不从,SQLS几乎完全是“自主”的决定是否使用索引或使用哪一个索引! 这是怎么回事呢? 让我们先来算一道题:如果某表的一条记录在磁盘上占用1000字节(1K)的话,我们对其中10字节的一个字段建立索引,那么该记录对应的索引大小只有10字节(0.01K)。上篇说过,SQLS的最小空间分配单元是“页(Page)”,一个页面在磁盘上占用8K空间,所以一页只能存储8条“记录”,但可以存储800条“索引”。现在我们要从一个有8000条记录的表中检索符合某个条件的记录(有Where子句),如果没有索引的话,我们需要遍历8000条×1000字节/8K字节=1000个页面才能够找到结果。如果在检索字段上有上述索引的话,那么我们可以在8000条×10字节/8K字节=10个页面中就检索到满足条件的索引块,然后根据索引块上的指针逐一找到结果数据块,这样I/O访问量肯定要少得多。 然而有时用索引还不如不用索引快! 同上,如果要无条件检索全部记录(不用Where子句),不用索引的话,需要访问8000条×1000字节/8K字节=1000个页面;而使用索引的话,首先检索索引,访问8000条×10字节/8K字节=10个页面得到索引检索结果,再根据索引检索结果去对应数据页面,由于是检索全部数据,所以需要再访问8000条×1000字节/8K字节=1000个页面将全部数据读取出来,一共访问了1010个页面,这显然不如不用索引快。 SQLS内部有一套完整的数据索引优化技术,在上述情况下,SQLS会自动使用表扫描的方式检索数据而不会使用任何索引。那么SQLS是怎么知道什么时候用索引,什么时候不用索引的呢?因为SQLS除了维护数据信息外,还维护着数据统计信息! 四、统计信息 打开企业管理器,单击“Database”节点,右击Northwind数据库→单击“属性”→选择“Options”选项卡,观察“Settings”下的各项复选项,你发现了什么? 从Settings中我们可以看到,在数据库中,SQLS将默认的自动创建和更新统计信息,这些统计信息包括数据密度和分布信息,正是它们帮助SQLS确定最佳的查询策略:建立查询计划和是否使用索引以及使用什么样的索引。 在创建索引时,SQLS会创建分布数据页来存放有关索引的两种统计信息:分布表和密度表。查询优化器使用这些统计信息估算使用该索引进行查询的成本(Cost),并在此基础上判断该索引对某个特定查询是否有用。 随着表中的数据发生变化,SQLS自动定期更新这些统计信息。采样是在各个数据页上随机进行。从磁盘读取一个数据页后,该数据页上的所有行都被用来更新统计信息。统计信息更新的频率取决于字段或索引中的数据量以及数据更改量。比如,对于有一万条记录的表,当1000个索引键值发生改变时,该表的统计信息便可能需要更新,因为1000 个值在该表中占了10%,这是一个很大的比例。而对于有1千万条记录的表来说,1000个索引值发生更改的意义则可以忽略不计,因此统计信息就不会自动更新。 至于它们帮助SQLS建立查询计划的具体过程,限于篇幅,这里就省略了,请有兴趣的朋友们自己研究。 顺便多说一句,SQLS除了能自动记录统计信息之外,还可以记录服务器中所发生的其它活动的详细信息,包括I/O 统计信息、CPU 统计信息、锁定请求、T-SQL 和 RPC 统计信息、索引和表扫描、警告和引发的错误、数据库对象的创建/除去、连接/断开、存储过程操作、游标操作等等。这些信息的读取、设置请朋友们在SQLS联机帮助文档(SQL Server Books Online)中搜索字符串“Profiler”查找。 五、索引的人工维护 上面讲到,某些不合适的索引将影响到SQLS的性能,随着应用系统的运行,数据不断地发生变化,当数据变化达到某一个程度时将会影响到索引的使用。这时需要用户自己来维护索引。 随着数据行的插入、删除和数据页的分裂,有些索引页可能只包含几页数据,另外应用在执行大量I/O的时候,重建非聚聚集索引可以维护I/O的效率。重建索引实质上是重新组织B树。需要重建索引的情况有: 1) 数据和使用模式大幅度变化; 2)排序的顺序发生改变; 3)要进行大量插入操作或已经完成; 4)使用I/O查询的磁盘读次数比预料的要多; 5)由于大量数据修改,使得数据页和索引页没有充分使用而导致空间的使用超出估算; 6)dbcc检查出索引有问题。 六、索引的使用原则 接近尾声的时候,让我们再从另一个角度认识索引的两个重要属性----唯一性索引和复合性索引。 在设计表的时候,可以对字段值进行某些限制,比如可以对字段进行主键约束或唯一性约束。 主键约束是指定某个或多个字段不允许重复,用于防止表中出现两条完全相同的记录,这样的字段称为主键,每张表都可以建立并且只能建立一个主键,构成主键的字段不允许空值。例如职员表中“身份证号”字段或成绩表中“学号、课程编号”字段组合。 而唯一性约束与主键约束类似,区别只在于构成唯一性约束的字段允许出现空值。 建立在主键约束和唯一性约束上的索引,由于其字段值具有唯一性,于是我们将这种索引叫做“唯一性索引”,如果这个唯一性索引是由两个以上字段的组合建立的,那么它又叫“复合性索引”。 注意,唯一索引不是聚集索引,如果对一个字段建立了唯一索引,你仅仅不能向这个字段输入重复的值。并不妨碍你可以对其它类型的字段也建立一个唯一性索引,它们可以是聚集的,也可以是非聚集的。 唯一性索引保证在索引列中的全部数据是唯一的,不会包含冗余数据。如果表中已经有一个主键约束或者唯一性约束,那么当创建表或者修改表时,SQLS自动创建一个唯一性索引。但出于必须保证唯一性,那么应该创建主键约束或者唯一性键约束,而不是创建一个唯一性索引。当创建唯一性索引时,应该认真考虑这些规则:当在表中创建主键约束或者唯一性键约束时, SQLS钭自动创建一个唯一性索引;如果表中已经包含有数据,那么当创建索引时,SQLS检查表中已有数据的冗余性,如果发现冗余值,那么SQLS就取消该语句的执行,并且返回一个错误消息,确保表中的每一行数据都有一个唯一值。 复合索引就是一个索引创建在两个列或者多个列上。在搜索时,当两个或者多个列作为一个关键值时,最好在这些列上创建复合索引。当创建复合索引时,应该考虑这些规则:最多可以把16个列合并成一个单独的复合索引,构成复合索引的列的总长度不能超过900字节,也就是说复合列的长度不能太长;在复合索引中,所有的列必须来自同一个表中,不能跨表建立复合列;在复合索引中,列的排列顺序是非常重要的,原则上,应该首先定义最唯一的列,例如在(COL1,COL2)上的索引与在(COL2,COL1)上的索引是不相同的,因为两个索引的列的顺序不同;为了使查询优化器使用复合索引,查询语句中的WHERE子句必须参考复合索引中第一个列;当表中有多个关键列时,复合索引是非常有用的;使用复合索引可以提高查询性能,减少在一个表中所创建的索引数量。 综上所述,我们总结了如下索引使用原则: 1)逻辑主键使用唯一的成组索引,对系统键(作为存储过程)采用唯一的非成组索引,对任何外键列采用非成组索引。考虑数据库的空间有多大,表如何进行访问,还有这些访问是否主要用作读写。 2)不要索引memo/note 字段,不要索引大型字段(有很多字符),这样作会让索引占用太多的存储空间。 3)不要索引常用的小型表 4)一般不要为小型数据表设置过多的索引,假如它们经常有插入和删除操作就更别这样作了,SQLS对这些插入和删除操作提供的索引维护可能比扫描表空间消耗更多的时间。 七、大结局 查询是一个物理过程,表面上是SQLS在东跑西跑,其实真正大部分压马路的工作是由磁盘输入输出系统(I/O)完成,全表扫描需要从磁盘上读表的每一个数据页,如果有索引指向数据值,则I/O读几次磁盘就可以了。但是,在随时发生的增、删、改操作中,索引的存在会大大增加工作量,因此,合理的索引设计是建立在对各种查询的分析和预测上的,只有正确地使索引与程序结合起来,才能产生最佳的优化方案。 一般来说建立索引的思路是: (1)主键时常作为where子句的条件,应在表的主键列上建立聚聚集索引,尤其当经常用它作为连接的时候。 (2)有大量重复值且经常有范围查询和排序、分组发生的列,或者非常频繁地被访问的列,可考虑建立聚聚集索引。 (3)经常同时存取多列,且每列都含有重复值可考虑建立复合索引来覆盖一个或一组查询,并把查询引用最频繁的列作为前导列,如果可能尽量使关键查询形成覆盖查询。 (4)如果知道索引键的所有值都是唯一的,那么确保把索引定义成唯一索引。 (5)在一个经常做插入操作的表上建索引时,使用fillfactor(填充因子)来减少页分裂,同时提高并发度降低死锁的发生。如果在只读表上建索引,则可以把fillfactor置为100。 (6)在选择索引字段时,尽量选择那些小数据类型的字段作为索引键,以使每个索引页能够容纳尽可能多的索引键和指针,通过这种方式,可使一个查询必须遍历的索引页面降到最小。此外,尽可能地使用整数为键值,因为它能够提供比任何数据类型都快的访问速度。 SQLS是一个很复杂的系统,让索引以及查询背后的东西真相大白,可以帮助我们更为深刻的了解我们的系统。一句话,索引就象盐,少则无味多则咸。 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_28052907/article/details/75194926。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-04-30 23:10:07
97
转载
转载文章
...描述,一边阅读、一边实践、一边理解,定能有意想不到的巨大收获!希望本系列博文能够得到广大园友的高度推荐。 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
转载
Impala
...che的一套开源分析型数据库系统,专为大数据处理而设计。它在获取数据的时候,耍了个小聪明,采用了缓存策略,这样一来就能更快地把数据喂给系统。同时,它还配备了一系列的优化手段,目的就是为了让你体验飞一般的速度,全面提升性能表现。本文将深入探讨Impala的缓存策略以及如何对其进行优化。 一、Impala的缓存策略 Impala采用了一种基于查询级别的缓存策略。当用户发动一个SQL查询,Impala这个小机灵鬼就会先把查询结果暂时存放在内存里头,这样一来,下次再有类似的查询需求时,就能嗖嗖地从内存中快速拿到数据了。另外,Impala还有一项很实用的功能——分片缓存,这就像是给特定的表或者查询结果准备了一个小仓库,能够把它们暂时存起来。这样一来,我们在管理内存资源时就能更加得心应手,效率自然蹭蹭往上涨啦! 代码示例: sql CREATE TABLE t1 (a INT, b STRING) WITH SERDEPROPERTIES ('serdeClassName'='org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe'); INSERT INTO TABLE t1 SELECT i, 'a' FROM generate_series(1, 10000)i; 上述代码创建了一个包含10000行的测试表t1,然后插入了一些测试数据。如果咱时常得从这个表格里头查数据,那咱们可以琢磨一下用分片缓存这招来给查询速度提提速。 sql SET hive.cbo.enable=true; SET hive.cbo.cacheIntermediateAggregates=true; 设置上述参数后,Hive会对聚合操作的结果进行缓存,从而提高查询速度。 二、如何优化Impala的缓存策略 对于Impala来说,优化缓存策略的关键在于合理分配内存资源,并选择合适的缓存类型。 1. 合理分配内存资源 Impala的默认配置可能会导致内存资源被过度占用,从而影响其他应用程序的运行。因此,我们需要根据实际需求调整Impala的内存配置。 bash set hive.exec.mode.local.auto=false; 不自动转成本地模式 set hive.server2.thrift.min.worker.threads=8; 增加线程数量 set hive.server2.thrift.max.worker.threads=64; 增加线程数量 上述代码通过修改Impala的配置文件来增加线程数量,从而提高内存利用率。 2. 选择合适的缓存类型 Impala提供了多种类型的缓存,包括基于表的缓存、基于查询的缓存和分区级缓存等。我们需要根据实际情况选择最合适的缓存类型。 sql CREATE TABLE t2 (a INT, b STRING) WITH CACHED AS SELECT FROM t1 WHERE b = 'a'; 上述代码创建了一个包含测试数据的新表t2,并将其缓存在内存中。由于t2表中的数据只包含一条记录,因此我们选择基于查询的缓存类型。 三、总结 通过本文的介绍,您应该对Impala的缓存策略有了更深入的理解,并学习到了一些优化缓存策略的方法。在实际动手操作的时候,我们得灵活应对,针对不同的应用场景做出适当的调整,这样才能确保效果杠杠的。
2023-07-22 12:33:17
550
晚秋落叶-t
Hadoop
在当今的大数据与机器学习领域,Hadoop作为基础架构的重要组成部分,其价值和应用不断深化。实际上,随着Apache Spark的崛起以及大数据处理技术的持续演进,许多企业和研究机构开始探索如何将Spark与Hadoop结合使用,以进一步提升大规模机器学习训练的效率。 据2022年最新报道,Cloudera公司发布的最新版CDP平台集成了Hadoop与Spark,实现了一站式的机器学习解决方案。通过利用Spark的内存计算优势和强大的数据处理能力,能够在保持Hadoop高扩展性、可靠性的基础上,显著加快机器学习模型训练速度,尤其对于迭代型算法如深度学习等有显著效果。 此外,近年来兴起的Kubernetes容器编排技术也在大数据生态中发挥着重要作用,它可以更好地管理运行在Hadoop集群上的分布式机器学习任务,确保资源的有效分配与动态调度。例如,借助Kubernetes,可以轻松部署和管理TensorFlow-on-Hadoop等项目,从而在Hadoop平台上无缝进行大规模深度学习训练。 深入探究,我们发现,尽管新的技术和框架层出不穷,但Hadoop的核心地位并未动摇,反而在与其他先进技术融合的过程中,不断展现出更强的生命力和更广泛的应用场景。未来,Hadoop将继续在大规模机器学习训练及其他复杂数据处理任务中扮演关键角色,并通过集成更多创新技术,赋能数据科学家高效挖掘出更多隐藏在海量数据中的宝贵信息。
2023-01-11 08:17:27
461
翡翠梦境-t
转载文章
在深入探讨了海量数据处理的基本方法后,我们了解到,随着数字化进程的加速和互联网技术的发展,大数据已经成为各行各业不可或缺的资源。近年来,国内外许多企业和研究机构不断突破海量数据处理的技术瓶颈,实现了更高效的数据挖掘与分析。 例如,在2022年,Apache Spark社区发布了Spark 3.2版本,进一步优化了其对大规模数据处理的能力,特别是对结构化、半结构化数据的支持更加完善,通过Catalyst优化器的升级以及动态分区剪枝等新特性,有效提升了处理海量数据时的性能表现。 此外,Google公司近期发布的关于Bloom Filter的新研究成果,揭示了一种新型布隆过滤器变体——Counting Bloom Filter with Carry Sketches(CBCS),能够在保持较低错误率的同时,更精准地统计大规模数据集中元素出现的次数,为解决海量数据判重问题提供了新的解决方案。 同时,针对分布式环境下数据存储与计算的需求,Hadoop生态系统的组件如HDFS和YARN也在持续演进中,以适应实时流处理、机器学习等新兴应用场景。而诸如Kafka、Flink等流处理框架的兴起,也为海量数据的实时分析提供了强大支持。 不仅如此,学术界对于Trie树、Bitmap等数据结构的研究也在不断深入,结合新型硬件如SSD、GPU等进行并行优化,使得这些经典数据结构在现代海量数据处理场景下焕发新生。未来,随着量子计算和边缘计算等前沿技术的发展,海量数据处理的方法将更加丰富多元,效率也将有质的飞跃。 综上所述,海量数据处理技术正以前所未有的速度发展和完善,从理论研究到工程实践,各类创新技术和解决方案层出不穷,为大数据时代的数据价值挖掘奠定了坚实基础。广大读者可以通过关注最新的科研成果、行业报告和技术博客,深入了解这一领域的发展趋势和应用案例,以便更好地应对和解决实际工作中的海量数据挑战。
2024-03-01 12:40:17
541
转载
Hadoop
Hadoop是什么?它的主要组件有哪些? 1. 引言 在大数据处理的世界里,Apache Hadoop无疑是最热门的技术之一。不过呢,对于那些还没尝过Hadoop这道技术大餐的朋友们来说,他们脑袋里可能会蹦出一连串问号:“哎,Hadoop究竟是个啥嘞?它究竟能干些啥事儿呀?还有啊,它最主要的组成部分都有哪些呢?”今天呐,咱们就一起撸起袖子,好好挖掘探究一下这些问题吧! 2. 什么是Hadoop? 简单来说,Hadoop是一种用于存储和处理大规模数据的开源框架。它的主要目标是解决海量数据存储和处理的问题。Hadoop这家伙,处理大数据的能力贼溜,现在早就是业界公认的大数据处理“扛把子”了! 3. Hadoop的主要组件有哪些? Hadoop的主要组件包括以下几个部分: 3.1 Hadoop Distributed File System (HDFS) HDFS是Hadoop的核心组件之一,它是基于Google的GFS文件系统的分布式文件系统。HDFS这小家伙可机灵了,它知道大文件是个难啃的骨头,所以就耍了个聪明的办法,把大文件切成一块块的小份儿,然后把这些小块分散存到不同的服务器上,这样一来,不仅能储存得妥妥当当,还能同时在多台服务器上进行处理,效率杠杠滴!这种方式可以大大提高数据的读取速度和写入速度。 3.2 MapReduce MapReduce是Hadoop的另一个核心组件,它是用于处理大量数据的一种编程模型。MapReduce的运作方式就像这么回事儿:它先把一个超大的数据集给剁成一小块一小块,然后把这些小块分发给一群计算节点,大家一起手拉手并肩作战,同时处理各自的数据块。最后,将所有结果汇总起来得到最终的结果。 下面是一段使用MapReduce计算两个整数之和的Java代码: java import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class WordCount { public static class TokenizerMapper extends Mapper { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(LongWritable key, Text value, Context context ) throws IOException, InterruptedException { String line = value.toString(); StringTokenizer itr = new StringTokenizer(line); while (itr.hasMoreTokens()) { word.set(itr.nextToken()); context.write(word, one); } } } public static class IntSumReducer extends Reducer { private IntWritable result = new IntWritable(); public void reduce(Text key, Iterable values, Context context ) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCount.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } 在这个例子中,我们首先定义了一个Mapper类,它负责将文本切分成单词,并将每个单词作为一个键值对输出。然后呢,我们捣鼓出了一个Reducer类,它的职责就是把所有相同的单词出现的次数统统加起来。 以上就是Hadoop的一些基本信息以及它的主要组件介绍。如果你对此还有任何疑问或者想要深入了解,欢迎留言讨论!
2023-12-06 17:03:26
408
红尘漫步-t
MySQL
...ySQL是一种普遍的关系型数据库管理系统,时常应用于构建Web应用程序。在构建或管理MySQL数据库时,时常需要查看MySQL的版本号。以下是一些方法来查找MySQL的版本号。 方法1:通过命令行查找MySQL版本号。 1. 启动终端或命令行窗口。 2. 键入命令 "mysql --version",然后按Enter键。 3. MySQL版本号将显示在命令行窗口中。 例如: $ mysql --version mysql Ver 14.14 Distrib 5.7.19, for Linux (x86_64) using EditLine wrapper 方法2:通过MySQL命令行客户端查找MySQL版本号。 1. 启动MySQL命令行客户端。 2. 键入命令 "SELECT VERSION();",然后按Enter键。 3. MySQL版本号将显示在MySQL命令行客户端中。 例如: mysql>SELECT VERSION(); +-------------------------+ | VERSION() | +-------------------------+ | 5.7.19-0ubuntu0.16.04.1 | +-------------------------+ 1 row in set (0.00 sec) 无论您选择哪种方法,从中获得的MySQL版本号都是相同的。查看MySQL版本号是一个重要的工作,因为MySQL的版本可能会改变,从而可能会引起应用程序或Web应用程序的行为也随之发生改变。
2023-10-03 21:22:15
106
软件工程师
MySQL
...幅增强等新特性,使得数据处理更为高效便捷。此外,MySQL 8.0在安全性方面新增了 caching_sha2_password 身份验证插件,有效提升了数据库账户的安全级别。 同时,随着云服务的发展,MySQL也在各大云平台如AWS RDS、阿里云RDS等上提供了更加灵活且易于管理的服务选项。企业用户可以根据自身需求选择适合的部署方式,实现资源按需分配与扩展。 而对于开发者而言,掌握MySQL优化技巧及其实战应用至关重要。例如,合理设计数据库表结构、熟练运用索引策略、适时进行查询优化等方法,能够在很大程度上提高MySQL数据库在高并发场景下的响应速度和稳定性。 总的来说,MySQL作为全球最广泛使用的开源关系型数据库之一,在不断迭代升级中持续赋能各行业业务发展,而深入理解和熟练掌握MySQL的各项功能,无疑将为企业和个人开发者在大数据时代带来更强竞争力。
2023-02-06 16:45:27
103
程序媛
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
groups user
- 显示指定用户的所属组。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"