前端技术
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
[Elasticsearch版本不匹配]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Maven
...完成、代码重构、集成版本控制等,旨在提高开发效率和代码质量。在文章中,IDEA自带了Maven工具,但有时可能会出现版本不匹配或配置问题,导致依赖包无法正常加载。 依赖包 , 依赖包是指在软件项目中,为了实现特定功能而引用的外部库或组件。在Java项目中,这些依赖通常通过Maven管理,存储在本地仓库或远程仓库中。当项目需要使用某个外部库时,只需在项目的配置文件(如pom.xml)中声明依赖,Maven就会自动下载并管理这些依赖包,确保项目能够顺利运行。如果IDEA自带的Maven版本不兼容或配置不当,可能会导致某些依赖包无法正确加载。
2024-12-13 15:38:24
117
风中飘零_
Apache Solr
...URL配置错误,或者版本不匹配。 - 磁盘空间不足:复制需要大量的磁盘空间,如果空间不足会导致复制失败。 - 权限问题:某些情况下,权限设置不当也会导致复制失败。 4. 解决方案 针对这些问题,我整理了一些解决方案,希望能帮助大家避免类似的麻烦。 4.1 网络问题 先说说网络问题吧,这可能是最头疼的一个。我碰到的问题是主节点和从节点之间的网络有时候会断开,结果复制任务就卡住了,甚至直接失败。解决方法如下: 1. 检查网络连接 确保主节点和从节点之间网络稳定,可以通过ping命令来测试。 2. 增加重试机制 可以在Solr配置文件中设置重试次数,比如: xml 00:00:30 true 5 60 4.2 配置错误 配置错误也很常见,尤其是对于新手来说。有个小窍门,在配置文件里多加点注释,这样就能大大降低出错的几率啦!比如: xml commit schema.xml,stopwords.txt http://localhost:8983/solr/collection1/replication http://localhost:8983/solr/collection1/replication 00:00:30 4.3 磁盘空间问题 磁盘空间不足也是常见的问题,尤其是在大规模数据量的情况下。解决方法是定期清理旧的索引文件,或者增加磁盘容量。Solr提供了清理旧索引的API,可以定时调用: bash curl http://localhost:8983/solr/collection1/admin/cores?action=UNLOAD&core=collection1&deleteIndex=true&deleteDataDir=true 4.4 权限问题 权限问题通常是因为用户没有足够的权限访问Solr API。解决方法是给相关用户分配正确的角色和权限。例如,在Solr的配置文件中设置用户权限: xml etc/security.json true 然后在security.json文件中添加用户的权限信息: json { "authentication": { "class": "solr.BasicAuthPlugin", "credentials": { "admin": "hashed_password" } }, "authorization": { "class": "solr.RuleBasedAuthorizationPlugin", "permissions": [ { "name": "access-replication-handler", "role": "admin" } ], "user-role": { "admin": ["admin"] } } } 5. 总结 通过上面的分享,希望大家都能够更好地理解和处理Apache Solr中的复制问题。复制虽然重要,但也确实容易出错。但只要我们细心排查,合理配置,还是可以解决这些问题的。如果你也有类似的经历或者更好的解决方案,欢迎在评论区留言交流! 最后,我想说的是,技术这条路真的是越走越远,每一个问题都是一次成长的机会。希望大家都能在技术之路上越走越远,越走越稳!
2025-03-11 15:48:41
91
星辰大海
Logstash
...将处理后的数据发送至Elasticsearch等存储或分析系统。 Sortfilter , Sortfilter是Logstash中的一种内置过滤器,用于对事件中的指定字段进行排序操作。它允许用户根据字段值的大小关系调整事件的顺序,对于时间戳不连续或者需要按照特定字段排序的日志数据处理尤为实用。然而,Sortfilter要求待排序字段的所有元素必须为同一类型,若遇到不同类型混合的数组字段,则无法直接进行排序操作。 Elastic Stack , Elastic Stack是一套开源的大数据搜索、分析和可视化平台,由Elasticsearch、Logstash、Kibana以及Beats等组件组成。其中,Logstash负责数据收集与预处理;Elasticsearch用作分布式搜索引擎及数据分析引擎;Kibana则提供基于Web的数据可视化界面;而Beats则是轻量级的数据传输工具。这些组件协同工作,共同实现了从数据收集、存储、检索到展示的一站式解决方案,在日志管理、监控报警、应用程序性能监控等多个场景下广泛应用。
2023-03-09 18:30:41
303
秋水共长天一色
ElasticSearch
...语。这就是为什么我对Elasticsearch产生了浓厚的兴趣。Elasticsearch是一个强大的搜索引擎,可以快速地处理大量数据并返回精确的结果。 然而,Elasticsearch的功能远不止于此。它还带来了一大堆给力的高级搜索功能,这些功能就像我们的数据管家,能帮我们更溜地找到想要的信息,更能高效地整理和管理数据,让一切都变得轻松简单。在这篇文章里,咱们要大展身手,好好探索一下Elasticsearch那些厉害的高级搜索技巧。我不仅会跟你叨叨理论知识,更会搬出实实在在的代码实例,让你亲眼看它们怎么实操上阵。 二、什么是Elasticsearch? Elasticsearch是一个开源的分布式搜索引擎。它最初由 Elasticsearch BV 开发,现在由阿里云进行维护和开发。Elasticsearch 是一个基于 Lucene 的搜索引擎,支持实时分析、跨索引搜索和地理空间搜索等功能。 三、高级搜索功能 1. Fuzzy 搜索 Fuzzy搜索是一种模糊匹配算法,可以在输入关键字时容忍一些拼写错误。这使得我们可以更轻松地找到与我们的查询相匹配的结果。 在Elasticsearch中,我们可以使用fuzziness选项启用Fuzzy搜索。下面是一个使用Fuzzy搜索的例子: php-template GET /my_index/_search { "query": { "multi_match": { "query": "some text", "fields": ["text"], "fuzziness": "auto" } } } 在这个例子中,我们正在搜索名为“my_index”的索引中的所有包含“some text”的文档。"Fuzziness"这个参数你要是设成“auto”,那就相当于告诉Elasticsearch:伙计,你看着办吧,根据查询字符串的长短自己挑个最合适的模糊匹配程度哈! 2. 近义词搜索 近义词搜索是指在一个查询中替换一个单词为其同义词的能力。这对于处理同义词丰富且变化多端的数据集非常有用。 在Elasticsearch中,我们可以使用synonyms选项启用近义词搜索。下面是一个使用近义词搜索的例子: json PUT /my_index/_settings { "analysis": { "analyzer": { "my_analyzer": { "tokenizer": "standard", "filter": [ { "type": "synonym", "synonyms_path": "/path/to/synonyms.txt" } ] } } } } POST /my_index/_doc { "text": "This is an example sentence." } 在这个例子中,我们首先创建了一个名为“my_analyzer”的分析器,该分析器使用标准分词器和一个加载了同义词的过滤器。然后,我们使用这个分析器来索引一条包含“example”单词的文档。当你在搜索时用上了“sample”这个同义词,Elasticsearch会超级给力地找出和你最初输入的那个查询一模一样的结果来。就像是有个贴心的小助手,无论你怎么变着花样描述,它都能准确理解你的意思,并且给你找出完全匹配的答案。 3. 值匹配搜索 值匹配搜索是指在查询中指定要匹配的具体值的能力。这对于处理类型明确的数据非常有用,例如日期、数字或地理位置等。 在Elasticsearch中,我们可以使用value_match选项启用值匹配搜索。下面是一个使用值匹配搜索的例子: json GET /my_index/_search { "query": { "bool": { "must": [ { "range": { "date_field": { "gte": "now-3d" } } }, { "match": { "string_field": "some text" } } ] } } } 在这个例子中,我们正在搜索名为“my_index”的索引中所有满足两个条件的文档:文档的“date字段”必须大于等于当前日期减去3天,并且文档的“string字段”必须包含“some text”。 四、总结 Elasticsearch不仅提供了基本的搜索功能,而且还提供了许多高级搜索功能。通过利用这些功能,我们可以更高效地搜索和管理我们的数据。 在未来的文章中,我们将继续探索更多的Elasticsearch功能,并提供更多的代码示例。感谢您的阅读,如果您有任何疑问或反馈,请随时告诉我。
2023-02-26 23:53:35
527
岁月如歌-t
Apache Solr
...提升实践能力。最近,Elasticsearch在其7.x版本中也对地理空间搜索进行了重大改进,引入了更强大的Geo-point数据类型以及增强的聚合和过滤功能(来源:Elastic官方博客)。这意味着开发者现在可以根据业务需求,在Solr和Elasticsearch之间做出更为精细的选择。 同时,大数据与AI技术在地理信息处理领域的融合愈发紧密。例如,Google Maps利用机器学习技术进行实时路况预测与智能路线规划,这启示我们在构建基于Solr的地理信息系统时,也可以尝试集成深度学习模型以优化地理位置查询结果,并实现更加精准的地理信息服务(参考:Google AI博客)。 另外,随着物联网、5G等新技术的发展,海量设备产生的实时地理位置数据为搜索引擎提出了新的挑战。有研究团队正在积极探索如何结合Apache Solr和其他开源工具,如Kafka和Spark,实现实时地理数据分析与可视化(来源:ACM SIGSPATIAL GIS会议论文集)。这对于智慧城市、物流跟踪、紧急救援等领域具有重要价值。 综上所述,深入挖掘Apache Solr地理搜索的应用潜力,并关注同类产品和技术的最新进展,将有助于我们在地理信息检索和分析方面保持领先优势。同时,随着AI和大数据技术的不断发展,未来地理搜索功能有望迎来更多创新应用场景和解决方案。
2024-03-06 11:31:08
405
红尘漫步-t
Apache Solr
...的乐观锁机制,也就是版本号控制这一招儿,来巧妙地应对这个问题。具体来说呢,就像每一份文档都有自己的身份证号码一样,它们各自拥有一个版本号字段,这个字段就叫做 _version_。每次我们对文档进行更新的时候,这个版本号就会往上加一,就像咱们小时候玩游戏升级打怪一样,每次升级都会经验值往上涨。要是有两个请求,它们各自带的版本号对不上茬儿,那么后到的那个请求就会被我们无情地拒之门外。这么做是为了避免数据被不小心覆盖或者丢失掉,就像你不会同时用两支笔在同一份作业上写字,以防搞乱一样。 java // 示例:尝试更新一个文档,包含版本号控制 SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", "1"); // 唯一键 doc.addField("_version_", 2); // 当前版本号 doc.addField("content", "new content"); UpdateRequest req = new UpdateRequest(); req.add(doc); req.setCommitWithin(1000); // 设置自动提交时间 solrClient.request(req); 3. 并发写入冲突引发的问题实例 设想这样一个场景:有两个并发请求A和B,它们试图更新同一个文档。假设请求A先到达,成功更新了文档并增加了版本号。这时,请求B才到达,但由于它携带的是旧的版本号信息,因此更新操作会失败。 java // 请求B的示例代码,假设携带的是旧版本号 SolrInputDocument conflictingDoc = new SolrInputDocument(); conflictingDoc.addField("id", "1"); // 同一唯一键 conflictingDoc.addField("_version_", 1); // 这是过期的版本号 conflictingDoc.addField("content", "conflicting content"); UpdateRequest conflictReq = new UpdateRequest(); conflictReq.add(conflictingDoc); solrClient.request(conflictReq); // 此请求将因为版本号不匹配而失败 4. 解决策略与优化方案 面对这种并发写入冲突导致的数据插入失败问题,我们可以从以下几个方面入手: - 重试策略:当出现版本冲突时,可以设计一种重试机制,让客户端获取最新的版本号后重新发起更新请求。但需要注意避免无限循环和性能开销。 - 分布式事务:对于复杂业务场景,可能需要引入分布式事务管理,如使用Solr的TransactionLog功能实现ACID特性,确保在高并发环境下的数据一致性。 - 应用层控制:在应用层设计合理的并发控制策略,例如使用队列、锁等机制,确保在同一时刻只有一个请求在处理特定文档的更新。 - 合理设置Solr配置:比如调整autoCommit和softCommit的参数,以减少因频繁提交而导致的并发冲突。 5. 总结与思考 在实际开发过程中,我们不仅要了解Apache Solr提供的并发控制机制,更要结合具体业务场景灵活运用,适时采取合适的并发控制策略。当碰上并发写入冲突,导致数据插不进去的尴尬情况时,咱们得主动出击,找寻并实实在在地执行那些能解决问题的好法子,这样才能确保咱们系统的平稳运行,保证数据的准确无误、前后一致。在摸爬滚打的探索旅程中,我们不断吸收新知识,理解奥秘,改进不足,这正是技术所散发出的独特魅力,也是咱们这群开发者能够持续进步、永不止步的原动力。
2023-12-03 12:39:15
536
岁月静好
RocketMQ
...应用程序所依赖的类库版本与当前Java运行环境(JRE)不匹配导致的问题。例如,RocketMQ 4.9.x版本需要Java 11及以上环境,若在Java 8环境中运行,由于新版本类库可能使用了旧版JRE不支持的特性,就会引发“UnsupportedClassVersionError”,表现为类加载失败,这便是Java类库兼容性问题的具体体现。 向下兼容原则 , 在软件开发领域,向下兼容原则是指新版本软件应当能够支持老版本软件的功能,并能正常处理由老版本创建的数据或执行的任务。在本文讨论中,强调在给系统升级换代时遵循“向下兼容”原则,意味着即使更新RocketMQ或其他组件版本,也要确保其能在现有的基础环境中稳定运行,不影响现有业务流程,避免因版本升级而产生的潜在风险和额外开销。
2023-05-24 22:36:11
187
灵动之光
Logstash
...多行的日志时,为了在Elasticsearch或其他分析工具中进行有效和准确的搜索、分析与可视化,将这些多行日志合并成单个事件就显得尤为重要。在ELK这个大名鼎鼎的套装(Elasticsearch、Logstash、Kibana)里头,Logstash可是个不可或缺的重要角色。它就像个超级能干的日志小管家,专门负责把那些乱七八糟的日志信息统统收集起来,然后精心过滤、精准传输。而在这个过程中,有个相当关键的小法宝就是内置的multiline codec或者filter插件,这玩意儿就是用来解决日志多行合并问题的一把好手。 1. 多行日志问题背景 在某些情况下,比如Java异常堆栈跟踪、长格式的JSON日志等,日志信息可能被分割到连续的几行中。要是不把这些日志合并在一起瞅,那就等于把每行日志都当做一个独立的小事去处理,这样一来,信息就很可能出现断片儿的情况,就像一本残缺不全的书,没法让我们全面了解整个故事。这必然会给后续的数据分析、故障排查等工作带来麻烦,让它们变得棘手不少。 2. 使用multiline Codec实现日志合并 示例1:使用input阶段的multiline codec 从Logstash的较新版本开始,推荐的做法是在input阶段配置multiline codec来直接合并多行日志: ruby input { file { path => "/path/to/your/logs/.log" start_position => "beginning" 或者是 "end" 以追加模式读取 codec => multiline { pattern => "^%{TIMESTAMP_ISO8601}" 自定义匹配下一行开始的正则表达式 what => "previous" 表示当前行与上一行合并 negate => true 匹配失败才合并,对于堆栈跟踪等通常第一行不匹配模式的情况有用 } } } 在这个例子中,codec会根据指定的pattern识别出新的一行日志的开始,并将之前的所有行合并为一个事件。当遇到新的时间戳时,Logstash认为一个新的事件开始了,然后重新开始合并过程。 3. 使用multiline Filter的旧版方案 在Logstash的早期版本中,multiline功能是通过filter插件实现的: ruby input { file { path => "/path/to/your/logs/.log" start_position => "beginning" } } filter { multiline { pattern => "^%{TIMESTAMP_ISO8601}" what => "previous" negate => true } } 尽管在最新版本中这一做法已不再推荐,但在某些场景下,你仍可能需要参考这种旧有的配置方法。 4. 解析多行日志实战思考 在实际应用中,理解并调整multiline配置参数至关重要。比如,这个pattern呐,它就像是个超级侦探,得按照你日志的“穿衣风格”准确无误地找到每一段多行日志的开头标志。再来说说这个what字段,它就相当于我们的小助手,告诉我们哪几行该凑到一块儿去,可能是上一个兄弟,也可能是下一个邻居。最后,还有个灵活的小开关negate,你可以用它来反转匹配规则,这样就能轻松应对各种千奇百怪的日志格式啦! 当你调试多行日志合并规则时,可能会经历一些曲折,因为不同的应用程序可能有着迥异的日志格式。这就需要我们化身成侦探,用敏锐的眼光去洞察,用智慧的大脑去推理,手握正则表达式的“试验田”,不断试错、不断调整优化。直到有一天,我们手中的正则表达式如同一把无比精准的钥匙,咔嚓一声,就打开了与日志结构完美匹配的那扇大门。 总结起来,在Logstash中处理多行日志合并是一个涉及对日志结构深入理解的过程,也是利用Logstash强大灵活性的一个体现。你知道吗,如果我们灵巧地使用multiline这个codec或者filter小工具,就能把那些本来七零八落的上下文信息,像拼图一样拼接起来,对齐得整整齐齐的。这样一来,后面我们再做数据分析时,不仅效率蹭蹭往上涨,而且结果也会准得没话说,简直不要太给力!
2023-08-19 08:55:43
249
春暖花开
.net
...构不受信任或主机名不匹配等原因引起的(情感化表达:就像你拿着一张无效的身份证明试图进入一个高度机密的区域,系统自然会拒绝你的请求)。 csharp // 示例:.NET中处理证书验证失败的代码示例 ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { if (sslPolicyErrors == SslPolicyErrors.None) return true; // 这里可以添加自定义的证书验证逻辑,比如检查证书指纹、有效期等 // 但请注意,仅在测试环境使用此方法绕过验证,生产环境应确保证书正确无误 Console.WriteLine("证书验证失败,错误原因:{0}", sslPolicyErrors); return false; // 默认情况下返回false表示拒绝连接 }; 2.2 协议版本不兼容 随着TLS协议的不断升级,旧版本可能存在安全漏洞而被弃用。这个时候,假如服务器傲娇地说,“喂喂,我得用更新潮、更安全的TLS版本才能跟你沟通”,而客户端(比如你手头那个.NET应用程序小家伙)却挠挠头说,“抱歉啊老兄,我还不会那种高级语言呢”。那么,结果就像两个人分别说着各自的方言,鸡同鸭讲,完全对不上频道,自然而然就连接不成功啦。 csharp // 示例:设置.NET应用支持特定的TLS版本 System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; 2.3 非法或损坏的证书链 有时,如果服务器提供的证书链不完整或者证书文件本身有问题,也可能导致SSL/TLS连接错误(探讨性话术:这就好比你拿到一本缺页的故事书,虽然每一页单独看起来没问题,但因为缺失关键章节,所以整体故事无法连贯起来)。 3. 解决方案与实践建议 - 更新系统和库:确保.NET Framework或.NET Core已更新到最新版本,以支持最新的TLS协议。 - 正确配置证书:服务器端应提供完整的、有效的且受信任的证书链。 - 严格控制证书验证:尽管上述示例展示了如何临时绕过证书验证,但在生产环境中必须确保所有证书都经过严格的验证。 - 细致排查问题:针对具体的错误提示和日志信息,结合代码示例进行针对性调试和修复。 总的来说,在.NET中处理SSL/TLS连接错误,不仅需要我们对协议有深入的理解,还需要根据实际情况灵活应对并采取正确的策略。当碰上这类问题,咱一块儿拿出耐心和细心,就像个侦探破案那样,一步步慢慢揭开谜团,最终,放心吧,肯定能找到解决问题的那个“钥匙线索”。
2023-05-23 20:56:21
439
烟雨江南
SpringCloud
...务提供者/消费者无法匹配异常 在分布式微服务架构的世界中,SpringCloud作为一款强大的一站式微服务解决方案框架,深受开发者喜爱。然而,在实际动手开发和部署的过程中,咱们可能会碰上个让人脑壳疼的难题——就是服务提供方和服务使用者之间无法顺利对上号、出现异常匹配的情况。嘿,伙计们,这次咱们一起揭开这个问题的神秘面纱,深入探索背后的真相。我还会亲自上阵,用实例代码给你们实操演示,教你们手把手搞定这类问题! 1. 异常现象简述 在SpringCloud体系中,服务提供者(Provider)会将自己的服务注册到服务中心(如Eureka或Nacos),而服务消费者(Consumer)则通过从服务中心拉取服务列表来调用对应的服务。当你遇到“服务提供者和消费者配对不上的问题”时,这通常就像是消费者在大超市里怎么也找不到自己需要的那个商品货架一样。具体表现可能是你在尝试调用某个服务时,系统突然像个淘气的小孩,抛出一句“找不到能用的实例,例如No instance available for ...”这样的错误消息来给你捣乱。 2. 常见原因剖析 2.1 服务注册失败 情景再现: 服务提供者启动后并未成功注册到服务中心。 java @SpringBootApplication @EnableDiscoveryClient // 启用服务注册与发现功能 public class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); } @Bean @LoadBalanced // 负载均衡注解,这里假设省略了,可能导致服务未正确注册 public RestTemplate restTemplate() { return new RestTemplate(); } } 在此示例中,若忘记添加@LoadBalanced注解,可能导致服务提供者虽然启动,但并未能成功注册到服务中心。 2.2 服务版本不匹配 思考过程: 服务提供者可能发布了新版本的服务,而消费者仍然使用旧版服务名进行调用。 yaml 消费者配置文件 spring: application: name: consumer-service cloud: nacos: discovery: server-addr: localhost:8848 注册中心地址 service: consumer-service: version: 1.0.0 若此处版本与提供者不一致,将导致无法匹配 2.3 服务实例状态异常 理解过程: 服务中心中的服务提供者实例可能因为网络、负载等问题处于下线或隔离状态,此时消费者也无法正常调用。 2.4 配置问题 探讨性话术: 检查消费者的依赖注入和服务引用是否正确,例如Feign、RestTemplate或OpenFeign的配置和使用: java @FeignClient(name = "provider-service", url = "${feign.client.provider.url}") public interface ProviderService { @GetMapping("/api") String callApi(); } 如果name值与提供者应用名称不匹配,或者url配置有误,也可能导致服务匹配异常。 3. 解决方案与防范措施 针对上述原因,我们可以采取以下措施: 1. 确保服务提供者的注册与发现功能启用且配置无误。 2. 在发布新版本服务时,同步更新消费者对服务版本的引用。 3. 定期监控服务中心,确保服务实例健康在线,及时处理异常实例。 4. 仔细检查并校验消费者服务引用的相关配置。 总结来说,面对SpringCloud环境下服务提供者与消费者无法匹配的异常问题,我们需要结合具体场景,深究背后的原因,通过对症下药的方式逐一排查并解决问题。同时呢,咱们也得时刻惦记着对微服务架构整体格局的把握,还有对其背后隐藏的那些玄机的深刻理解,这样一来,才能更好地对付未来可能出现的各种技术难题,就像是个身经百战的老兵一样。
2023-02-03 17:24:44
128
春暖花开
Mahout
...与Spark集成时的版本冲突问题深度解析 1. 引言 Apache Mahout,这个强大的机器学习库,在大数据处理领域一直备受瞩目。Spark这个家伙,可厉害了,人家是个超级给力、操作还贼简单的分布式计算框架。现如今,越来越多的数据科学家和工程师们发现这家伙好使,都把它当成了心头好,处理数据时的首选法宝。当这两个家伙碰头,那肯定能碰撞出炫酷的火花来。不过,在我们实际做项目整合的时候,Mahout和Spark版本之间的兼容性问题却像个小捣蛋鬼,时不时地就给我们带来些小麻烦。本文将深入探讨这一主题,通过实例代码及详细分析,揭示可能遇到的问题以及应对策略。 2. Mahout与Spark的结合 优势与挑战 2.1 优势 集成Mahout与Spark后,我们可以利用Spark的并行处理能力来大幅提升Mahout算法的执行效率。例如,以下是一段使用Mahout-on-Spark实现协同过滤推荐算法的基础代码示例: scala import org.apache.mahout.sparkbindings._ import org.apache.mahout.math.drm._ val data: RDD[Rating] = ... // 初始化用户-物品评分数据 val drmData = DistributedRowMatrix(data.map(r => (r.user, r.product, r.rating)).map { case (u, i, r) => ((u.toLong, i.toLong), r.toDouble) }, numCols = numProducts) val model = ALS.train(drmData, rank = 10, iterations = 10) 2.2 挑战 然而,看似美好的融合背后,版本兼容性问题如同暗礁般潜藏。你知道吗,Mahout和Spark这两个家伙一直在不停地更新升级自己,就像手机系统一样,隔段时间就蹦出个新版本。这样一来呢,新版的接口或者内部构造可能就会变变样,这就意味着不是所有版本都能无缝衔接、愉快合作的,有时候也得头疼一下兼容性问题。如若不慎选择不匹配的版本组合,可能会出现运行错误、性能低下甚至完全无法运行的情况。 3. 版本冲突实例及其解决之道 3.1 实际案例 假设我们在一个项目中尝试将Mahout 0.13.x与Spark 2.4.x进行集成,可能会遇到如下错误提示(这里仅为示例,并非真实错误信息): Exception in thread "main" java.lang.NoSuchMethodError: org.apache.spark.rdd.RDD.org$apache$spark$rdd$RDD$$sc()Lorg/apache/spark/SparkContext; 这是因为Mahout 0.13.x对Spark的支持仅到2.3.x版本,对于Spark 2.4.x的部分接口进行了更改,导致调用失败。 3.2 解决策略 面对这类问题,我们需要遵循以下步骤来解决: - 确认兼容性:查阅Mahout官方文档或相关社区资源,明确当前Mahout版本所支持的Spark版本范围。 - 降级或升级:根据兼容性范围,决定是回退Spark版本还是升级Mahout版本以达到兼容。 - 依赖管理:在构建工具如Maven或SBT中,精确指定对应的依赖版本,确保项目中所有组件版本一致。 - 测试验证:完成上述操作后,务必进行全面的功能与性能测试,确保系统在新的版本环境中稳定运行。 4. 结论与思考 尽管Mahout与Spark集成过程中的版本冲突可能会带来一些困扰,但只要我们理解其背后的原理,掌握正确的排查方法,这些问题都是可预见且可控的。所以,在我们实际动手开发的时候,千万要像追星一样紧盯着Mahout和Spark这些技术栈的版本更新,毕竟它们一有动静,可能就会影响到兼容性。要想让Mahout和Spark这对好搭档火力全开,就得提前把这些因素琢磨透彻了。 以上内容仅是一个简要的探讨,实际开发过程中可能还会遇到更多具体问题。记住啊,当咱们碰上那些棘手的技术问题时,千万要稳住心态,有耐心去慢慢摸索,而且得乐在其中,把解决问题的过程当成一场冒险探索。这正是编写代码、开发软件让人欲罢不能的魅力所在!
2023-03-19 22:18:02
80
蝶舞花间
Maven
...素属性值、标签闭合、版本号、依赖关系等方面。 示例:错误的pom.xml配置可能导致无法识别的元素或属性。 xml com.example example-module unknown-version 这里,属性值未指定,导致Maven无法识别该版本信息。 2. 命令行参数错误 在执行Maven命令时输入的参数不正确或拼写错误。 示例:错误的命令行参数可能导致构建失败。 bash mvn compile -Dsome.property=wrong-value 这里的参数-Dsome.property=wrong-value中property的值可能与实际配置不匹配,导致Maven无法识别或处理。 3. 依赖冲突 多个版本的依赖包共存,且版本不兼容。 示例:两个依赖包同时声明了相同的类名或方法名,但版本不同,可能会引发编译错误。 xml org.example example-library 1.0.0 org.example example-library 1.0.1 四、解决方案与优化建议 1. 检查pom.xml文件 - 确保所有元素闭合、属性值正确。 - 使用IDE的自动完成功能或在线工具验证pom.xml的语法正确性。 2. 修正命令行参数 - 确认参数的拼写和格式正确。 - 使用Maven的help:effective-pom命令查看实际生效的pom.xml配置,确保与预期一致。 3. 解决依赖冲突 - 使用标签排除不必要的依赖。 - 更新或降级依赖版本以避免冲突。 - 使用Maven的dependency:tree命令查看依赖树,识别并解决潜在的冲突。 五、总结与反思 面对“Error:The project has a build goal with an invalid syntax”的挑战,关键在于细致地检查配置文件和构建命令,以及理解依赖关系。每一次遇到这样的错误,都是对Maven配置知识的深化学习机会。哎呀,你知道吗?就像你练习弹吉他一样,多用多练,咱们用Maven这个工具也能越来越顺手!它能帮咱们开发时节省不少时间,就像是有了个超级助手,能自动搞定那些繁琐的构建工作,让咱们的项目推进得飞快,没有那么多绊脚石挡道。是不是感觉挺酷的?咱们得好好加油,让这玩意儿成为咱们的拿手好戏! 六、结语 Maven作为项目构建管理工具,虽然强大且灵活,但也伴随着一定的复杂性和挑战。嘿!兄弟,这篇文章就是想给你支点招儿,让你在开发过程中遇到问题时能更顺手地找到解决方法,让编程这个事儿变得不那么头疼,提升你的码农体验感。别再为那些小bug烦恼了,跟着我的节奏,咱们一起搞定代码里的小麻烦,让编程之路畅通无阻!嘿,兄弟!听好了,每当你碰上棘手的问题,那可是你升级技能、长本事的绝佳机会!别急,拿出点好奇心,再添点耐心,咱们一起动手,一步步地去解谜,去学习,去挑战。就像在探险一样,慢慢你会发现自己的开发者之路越走越宽广,越来越精彩!所以啊,别怕困难,它们都是你的成长伙伴,加油,咱们一起成为更棒的开发者吧!
2024-08-09 16:06:13
93
初心未变
ElasticSearch
..._index: 一次ElasticSearch的实战复盘 一、问题初现 我的代码出了什么问题? 嘿,朋友们,我最近在用ElasticSearch做数据索引的时候,遇到了一个特别让人抓狂的问题——“Failed to bulk index documents into index my_index”。这就跟我在跑马拉松的时候鞋带突然散了似的,不仅跑得磕磕绊绊,连带着心里也一阵慌乱,开始怀疑自己是不是天生不适合这项运动。 当时我的代码是这样的: python from elasticsearch import Elasticsearch es = Elasticsearch() actions = [ { "_index": "my_index", "_id": "1", "_source": {"name": "John", "age": 30} }, { "_index": "my_index", "_id": "2", "_source": {"name": "Jane", "age": 25} } ] response = es.bulk(index="my_index", body=actions) print(response) 结果呢?直接报错:“Failed to bulk index documents into index my_index”。我当时就纳闷了,到底哪儿出错了呢?是数据格式搞拧巴了,还是索引没弄对?要不就是我自己写的代码坑太多了?那种感觉啊,就好比你在厨房按着菜谱一步一步做菜,结果一开锅,发现把一顿饭整成了糊锅底的“黑暗料理”,真是欲哭无泪啊! 二、初步排查 从错误信息入手 既然报错了,那我们就得从错误信息入手。首先,我们得看看ElasticSearch的日志,这是排查问题的第一步。日志里头一般会写得更详细一点,像是到底哪里错了、错得有多惨这种,还有那个堆栈信息啥的,看得人头都大了,但有时候不看又不行啊! 我先打开了ElasticSearch的日志文件(一般在/var/log/elasticsearch/目录下),然后发现日志里显示了一个错误:“MapperParsingException[failed to parse]”。看到这个,我就明白了,可能是数据格式有问题。 这时候我开始反思:是不是我的数据结构不符合ElasticSearch的映射规则?于是我又仔细检查了一下我的数据结构,发现确实有一个字段的数据类型没有定义好。比如说啊,我有个字段叫age,本来应该是整数类型的,但之前手滑写成字符串了,真是自己给自己挖坑。 修正后的代码如下: python actions = [ { "_index": "my_index", "_id": "1", "_source": {"name": "John", "age": 30} 确保age是整数类型 }, { "_index": "my_index", "_id": "2", "_source": {"name": "Jane", "age": 25} } ] 再次运行代码后,果然不再报错了。这就算是舒了口气吧,不过也给我提了个醒:用 ElasticSearch 做批量索引的时候,这数据格式啊,真的一点都不能含糊,不然分分钟让你抓狂! 三、深入分析 为什么会出现这种问题? 虽然问题解决了,但作为一个喜欢刨根问底的人,我还是想知道为什么会发生这样的事情。说白了,就是下次再碰到这种事儿,我可不想抓耳挠腮半天还搞不定,希望能一下子就找到路子! 首先,我想到了ElasticSearch的映射机制。Elasticsearch 会检查每个字段的类型,就像老师检查作业一样认真。要是你传的数据类型跟它预想的对不上号,它就会直接“翻脸”,给你抛个 MapperParsingException 错误,仿佛在说:“哎哟喂,这啥玩意儿?重写!”比如说啊,你有个字段叫age(年龄),本来应该填数字的,结果你非得塞个字符串进去,那ElasticSearch就直接不认你的文档,直接拒收,根本不带商量的! 其次,我还想到,ElasticSearch的bulk API其实是非常强大的,但它也有自己的规则。比如,bulk API要求每条文档必须包含_index、_type(虽然现在已经被废弃了)和_source字段。如果你漏掉了某个字段,或者字段名拼写错误,都会导致批量索引失败。 最后,我还注意到,ElasticSearch的bulk API是基于HTTP协议的,这意味着它对网络环境非常敏感。要是你的网络老是断线,或者你等了半天也没收到回应,那可能就搞不定批量索引这事啦。
2025-04-20 16:05:02
63
春暖花开
Gradle
...2.1 Gradle版本不匹配 有时候,你的React Native版本和Gradle版本可能不兼容。比如说啊,React Native从0.60版本开始搞了个自动链接的功能,挺方便的。但你要注意啦,如果你用的Gradle版本太老了,那可能就会出问题,一些依赖项就装不全或者装不好,最后各种报错啥的,真是让人头大。嘿,之前我也碰上过这么个事儿!那时候我的 React Native 版本已经升到 0.63 了,结果 Gradle 还是老版本,就跟手机升级了系统,但壳子还是原来的那个一样,看着就别扭啊!解决方法很简单,只需要升级Gradle到最新版本即可。 代码示例: gradle // build.gradle 文件中的配置 buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:4.2.0' // 升级到最新版本 } } 2.2.2 环境变量未配置 另一个常见的问题是环境变量没有正确配置。Gradle需要知道一些关键路径,比如Android SDK的位置。要是你忘了配这些路径,Gradle 就像没找到钥匙一样,干着急也使不上劲,最后只能眼睁睁看着构建任务挂掉。 代码示例: bash 设置环境变量 export ANDROID_HOME=/path/to/your/android/sdk export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools 2.2.3 缓存问题 Gradle有一个缓存机制,有时候这个缓存可能会出问题。比如说啊,有个依赖包老是下不下来,Gradle就一直在那儿较真儿,不停地重试,就跟个倔强的小孩似的,怎么劝都不停,最后还是没搞掂。这时,你可以尝试清理缓存并重新构建项目。 代码示例: bash 清理Gradle缓存 cd android ./gradlew clean --- 3. 解决方案 动手实践的快乐 3.1 第一步:检查Gradle版本 既然Gradle版本可能是罪魁祸首,我们首先要检查一下它的版本是否符合要求。打开android/build.gradle文件,找到classpath部分,确保它指向的是最新的Gradle版本。 代码示例: gradle dependencies { classpath 'com.android.tools.build:gradle:7.0.2' // 使用最新版本 } 如果版本过低,可以直接升级到最新版本。升级后,记得同步项目并重新构建。 3.2 第二步:配置环境变量 接下来,检查你的环境变量是否配置正确。尤其是Android SDK的路径,必须指向真实的SDK目录。如果你不确定路径,可以去Android Studio中查看。 代码示例: bash 配置环境变量 export ANDROID_HOME=/Users/username/Library/Android/sdk export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools 配置完成后,重启终端并运行项目,看看问题是否解决了。 3.3 第三步:清理缓存 如果前面两步都没有解决问题,可能是Gradle缓存出了问题。这时候,我们需要手动清理缓存。 代码示例: bash 进入Android目录并清理缓存 cd android ./gradlew clean 清理完成后,重新运行项目,看看是否能正常安装App。 --- 4. 总结与反思 成长的足迹 通过这次经历,我深刻体会到,React Native开发不仅仅是写代码那么简单,还需要对Gradle有深入的理解。Gradle虽然强大,但也非常复杂,稍有不慎就会出问题。不过,只要我们保持耐心,一步步排查问题,总能找到解决方案。 最后,我想说的是,开发过程中遇到问题并不可怕,可怕的是失去信心。每一次解决问题的过程,都是我们成长的机会。希望能帮到你,让你在碰到这些问题的时候,别再绕那么多弯子了,赶紧找到症结,把事情搞定! 如果你还有其他疑问,欢迎随时交流!让我们一起在React Native的世界里探索更多可能性吧!
2025-04-15 16:14:29
35
青山绿水_
Mongo
...确保它们与当前需求相匹配。 - 使用角色聚合:考虑使用 MongoDB 的角色聚合功能来简化权限管理。 五、总结与反思 在 MongoDB 中管理索引权限是一个既关键又细致的过程。哎呀,兄弟!掌握并恰到好处地运用这些招数,不仅能让你在处理数据库这事儿上效率爆棚,还能给你的系统安全和稳定打上一个大大的保险扣儿。就像是有了秘密武器一样,让数据跑得快又稳,而且还能防着那些不怀好意的小坏蛋来捣乱。这样一来,你的数据保管工作就不仅是个技术活,还成了守护宝藏的秘密行动呢!哎呀,你遇到了“IndexBuildingPrivilegeNotFound”的小麻烦?别急嘛,我来给你支个招!按照我刚刚说的步骤一步步来,就像解密游戏一样,慢慢找啊找,你会发现那个藏起来的小秘密。说不定,问题就在这儿呢!找到原因了,解决起来自然就快多了,就像解开了一道数学难题,是不是超有成就感的?别忘了,耐心是关键,就像慢慢炖一锅好汤,火候到了,味道自然就出来了。加油,你一定行的!嘿!兄弟,听好了,每次碰上难题,那都是咱们提升自己,长知识的好时机,就像我们在数据库这片大海上航行,每一步都让咱们更懂水性,越来越厉害! --- 通过本文的探索,我们不仅解决了“IndexBuildingPrivilegeNotFound”这一常见问题,还深入了解了索引在数据库性能优化中的重要性,以及如何通过正确的权限管理和配置来确保数据库操作的顺利进行。希望这篇文章能为 MongoDB 用户提供有价值的参考,共同提升数据库管理的效率和安全性。
2024-10-14 15:51:43
88
心灵驿站
Apache Lucene
...va社区也不断推出新版本,带来了诸多改进和新特性,使得开发者能够更高效地使用Lucene和避免常见的编程陷阱。 最近的一项研究显示,企业在构建搜索功能时,往往面临着性能瓶颈和用户体验问题。而Lucene凭借其强大的索引能力和灵活的搜索选项,成为了许多企业的首选解决方案。然而,随着数据量的激增,如何优化索引和查询性能成为了一个亟待解决的问题。例如,Netflix在其博客中分享了如何利用Lucene和Elasticsearch构建高效搜索系统的经验,特别强调了索引合并和缓存机制的重要性。 同时,Java 17的发布也为开发者提供了新的工具和改进,如更强的类型推断和更好的性能优化。这些新特性使得处理NullPointerException等常见异常变得更加容易,从而提升了代码的质量和稳定性。根据Oracle官方文档,Java 17引入了若干新特性,包括密封类(Sealed Classes)、记录类型(Record Patterns)等,这些都可以帮助开发者更安全地编写代码。 此外,对于那些正在寻找更强大、更易于扩展的搜索解决方案的企业而言,基于Lucene的分布式搜索系统,如Solr和Elasticsearch,正变得越来越受欢迎。这些系统不仅提供了高度的可伸缩性和容错性,还能通过集群管理工具轻松地进行部署和维护。例如,Elasticsearch的官方文档中详细介绍了如何使用Kubernetes进行部署,这为企业提供了更为便捷的解决方案。 综上所述,无论是通过优化现有技术还是采用新兴工具,企业都能够更好地应对大数据时代的挑战,提供更快、更准确的搜索服务。而对于开发者而言,掌握最新的编程语言特性和搜索技术,将有助于他们在竞争激烈的市场中脱颖而出。
2024-10-16 15:36:29
88
岁月静好
Gradle
...可能是由于依赖冲突、版本不兼容或是网络问题导致的。 分析原因:深入问题的核心 构建失败的原因多种多样,以下是一些常见的原因及其分析: - 依赖冲突:项目中多个模块或外部库之间存在版本冲突。 - 版本不兼容:依赖的某个库的版本与项目本身或其他依赖的版本不匹配。 - 网络问题:Gradle 无法从远程仓库下载所需的依赖,可能是由于网络连接问题或远程服务器访问受限。 - 配置错误:Gradle 的构建脚本中可能存在语法错误或逻辑错误,导致构建过程无法正常进行。 解决策略:逐步排查与修复 面对构建失败的情况,我们可以采取以下步骤进行排查与修复: 1. 检查错误日志 仔细阅读错误信息,了解构建失败的具体原因。 2. 清理缓存 使用 gradlew clean 命令清除构建缓存,有时候缓存中的旧数据可能导致构建失败。 3. 更新依赖 检查并更新所有依赖的版本,确保它们之间不存在冲突或兼容性问题。 4. 调整网络设置 如果错误信息指向网络问题,尝试更换网络环境或调整代理设置。 5. 验证构建脚本 审查 .gradle 文件夹下的 build.gradle 或 build.gradle.kts 文件,确保没有语法错误或逻辑上的疏漏。 6. 使用调试工具 利用 Gradle 提供的诊断工具或第三方工具(如 IntelliJ IDEA 的 Gradle 插件)来辅助定位问题。 示例代码:实践中的应用 下面是一个简单的示例,展示了如何在 Gradle 中配置依赖管理,并处理可能的构建失败情况: groovy plugins { id 'com.android.application' version '7.2.2' apply false } android { compileSdkVersion 31 buildToolsVersion "32.0.0" defaultConfig { applicationId "com.example.myapp" minSdkVersion 21 targetSdkVersion 31 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation 'androidx.appcompat:appcompat:1.4.2' implementation 'com.google.android.material:material:1.4.0' } // 简单的构建任务配置,用于演示 task checkDependencies(type: Check) { description = 'Checks dependencies for any issues.' classpath = configurations.compile.get() } 在这个示例中,我们定义了一个简单的 Android 应用项目,并添加了对 AndroidX 库的基本依赖。哎呀,你这项目里的小伙伴们都还好吗?对了,咱们有个小任务叫做checkDependencies,就是专门用来查一查这些小伙伴之间是不是有啥不和谐的地方。这事儿挺重要的,就像咱们定期体检一样,能早点发现问题,比如某个小伙伴突然闹脾气不干活了,或者新来的小伙伴和老伙计们不太合拍,咱都能提前知道,然后赶紧处理,不让事情闹得更大。所以,这个checkDependencies啊,其实就是咱们的一个小预防针,帮咱们防患于未然,确保项目运行得顺溜溜的! 结语 构建过程中的挑战是编程旅程的一部分,它们不仅考验着我们的技术能力,也是提升解决问题技巧的机会。通过细致地分析错误信息、逐步排查问题,以及灵活运用 Gradle 提供的工具和资源,我们可以有效地应对构建失败的挑战。嘿!兄弟,听好了,每次你栽跟头,那都不是白来的。那是你学习、进步的机会,让咱对这个叫 Gradle 的厉害构建神器用得更溜,做出超级棒的软件产品。别怕犯错,那可是通往成功的必经之路!
2024-07-29 16:10:49
497
冬日暖阳
RabbitMQ
...Q发布了3.10.0版本,引入了多项改进和新特性,其中包括增强的安全性和性能优化。这一版本特别强调了对大规模分布式系统的支持,旨在帮助企业更好地应对高并发场景下的消息传递挑战。 根据《InfoQ》报道,RabbitMQ 3.10.0版本引入了新的安全机制,增强了对TLS/SSL的支持,使得消息传输更加安全可靠。此外,该版本还优化了消息路由算法,提高了消息传递效率。这对于金融、电商等需要处理大量实时交易的企业来说尤为重要。 同时,《DZone》的一篇文章指出,RabbitMQ的新版本在集群管理方面也有所改进,提供了更强大的监控和管理工具。这使得运维人员可以更方便地进行故障排查和性能调优。对于正在考虑升级RabbitMQ版本的企业而言,这些改进无疑是一个好消息。 然而,正如我们在文章中所讨论的,版本更新也伴随着潜在的风险。企业在升级过程中需要仔细评估新版本带来的变化,确保代码和配置文件能够正确兼容。建议在正式部署前,进行充分的测试,以避免出现由于版本不匹配导致的意外问题。 总之,RabbitMQ 3.10.0版本的发布为企业提供了更多选择,但也提醒我们,技术的演进需要持续关注和学习。只有不断适应新技术的发展,才能确保业务系统的稳定性和可靠性。
2025-03-12 16:12:28
105
岁月如歌
ElasticSearch
如果你已经是elasticsearch的使用大牛,本篇文章对你不会有什么收益。如果你要做一个搜索功能,不知道如何选型,那你可以参考一下本文。 1. 可选方案 如果你需要做一个搜索功能,这时候你可能会想到很多实现方法: 比如你的底层数据库用的是sql数据库(比如mysql):你可能会想到在对应字段上使用field1 like '%?%',?即用户输出的关键词 比如你的底层数据库用的是mongo:你可能会想到在对应字段上使用db.collection.find({ "field1": { $regex: /aaa/ } })做查询,aaa即用户输入的关键词 比如你的底层数据库用的是elasticsearch:那厉害了,专业全文搜索神奇,全文搜索或搜索相关的需求使用elasticsearch绝对是最合适的选择 比如你的底层数据库用的是hive、impala、clickhouse等大数据计算引擎:鸟枪换炮,其实用作全文索引和搜索的场景并不合适,你可能依旧会使用sql数据库那样用like做交互 2. 方案选择 调研之后,可能会发现对于数据量相对大一点的搜索场景,在当下流行的数据库或计算引擎中,elasticsearch是其中最合适的解决方案。 无论是sql的like、还是mongo的regex,在线上环境下,数据量较多的情况下,都不是很高效的查询,甚至有的公司的dba会禁止在线上使用类似的查询语法。 与elasticsearch是“亲戚”的,大家还常提到lucene、solr,但是无论从现在的发展趋势还是公司运维人才的储备(不得不说当下的运维人才中,对es熟悉的人才会更多一些),elasticsearch是相对较合适的选择。 一些大数据计算引擎,其实更多的适合OLAP场景。当然也完全可以使用,因为比如clickhouse、starrocks等的查询速度已经发展的非常快。但你会发现在中文分词搜索上,实现起来有一定困扰。 所以,如果你不差机器,首选方案还是elasticsearch。 3. elasticsearch的适用场景 3.1 经典的日志搜索场景 提到elasticsearch不得不提到它的几个好朋友: 一些公司里经常用elasticsearch来收集日志,然后用kibana来展示和分析。 展开来说,举个例子,你的app打印日志打印到了线上日志文件,当app出现故障你需要做定位筛查的时候,可能需要登录线上机器用grep命令各种查看。 但如果你不差机器资源,可以搭建上述架构,app的日志会被收集到elasticsearch中,最终你可以在kibana中查看日志,kibana里面可以很方面的做各种筛查操作。 这个流畅大概是这样的: 3.2 通用搜索场景 但是没有上图的beats、logstash、kibana,elasticsearch可以自己工作吗?完全可以的! elasticsearch也支持单机部署,数据规模不是很大的情况下,表现也是不错的。所以,你也不用担心因为自己机器资源不够而对elasticsearch望而却步。当然,单机部署的情况下,更多的适合自己玩,对于可靠性的要求就不能太苛刻了。 如果你在用宝塔,那你可以在宝塔面板,左侧“软件商店”中直接找到elasticsearch,并“没有痛苦”的安装。 本篇文章主要讨论选型,所以不涉及安装细节。 3.2.1 性能顾虑 上面提到了“表现”,其实性能只是elasticsearch的一个方面,主要你的机器资源足够(机器资源?对,包括你的机器个数,elasticsearch可以非常方便的横向扩展,以及单机的配置,cpu+内存,内存越高越好,elasticsearch比较吃内存!),它一定会给你很好的性能反应。试想,公司里的app打印线上日志的行数其实可比一般业务系统产生的订单数量要大很多很多,elasticsearch都可以常在日志的实时分析,所以如果你要做通用场景,而且机器资源不是问题,这是完全行得通的。 3.2.2 易用性和可玩性 此外,在使用elasticsearch的时候,会有很多的可玩性。这里不引经据典,呈现很多elasticsearch官方文章的列举优秀特性(当然,确实很优秀!)。 这里举几个例子: (1)中文分词:第一章提到的其它引擎几乎很难实现,elasticsearch对分词器的支持是原生的,因为elasticsearch天生就为全文索引而生,elasticsearch的汉语名字就是“弹性搜索”。这家伙可是专门搞搜索的! 有的朋友可能不了解分词器,比如你的一个字段里存储“今天我要吃冰激凌”,在分词器的加持下,es最终会存储为“今天|我|要|吃|冰激凌”,并且使用倒排索引的形式进行存储。当你搜索“冰激凌”的时候,可以很快的反馈回来。 关于elasticsearch的原理,这里不展开说明,分词器和倒排索引是elasticsearch的最基本的概念。如果有不了解的朋友,可以自行百度一下。而且这两个概念,与elasticsearch其实不挂钩,是搜索中的通用概念。 关于倒排索引,其核心表现如下图: 如果你要用mysql、mongo实现中文分词,这......其实挺麻烦的,可能在后面的版本支持中会实现的很好,但在当前的流行版本中,它们对中文分词是不够友好的。 mysql5.7之后支持外挂第三方分词器,支持中文分词。而在数据量较大的情况下,mysql的多机器部署几乎很难实现,elasticsearch可以很容易的水平扩展。 mongo支持西方语言的分词,但不支持中文、日语、汉语等东方语言,你需要在自己的逻辑代码中实现分词器。 ngram分词,你看看效果:依旧是“今天我要吃冰激凌”,ngram二元分词后即将得到结果“今天、天我、我要、要吃、吃冰、冰激、激凌”。这....,那你搜索冰激凌就搜不出来!咋办呢,当然可以使用三元分词。但是更好的解决方案还是中文分词器,但它们原生并不支持的。 (2)自定义排名场景:比如你的搜索“冰激凌”,结果中返回了有10条,这10条应该有你想对它指定的顺序。最简单的就是用默认的得分,但是如果你想人为干预这个得分怎么办? elasticsearch支持function_score功能(可以不用,这个是增强功能),es会在计算最终得分之前回调这个你指定的function_score回调函数,传入原始得分、行的原始数据,你可以在里面做计算,比如查询其它参考表、或查看是否是广告位,以得到新的score返回给用户。 function_scrore的功能不展开描述,是一个在自定义得分场景下十分有用又简单易用的功能!下面是一个使用示例,不仅如此,它是支持自定义函数的,自由度非常高。 (3)文本高亮:你用mysql或mongo也可以实现,比如用户搜索“冰激凌”,你只需要在逻辑代码中对“冰激凌”替换为“<span class='highlight-term'>冰激凌</span>”,然后前端做样式即可。但如果用户搜索了“好吃的冰激凌”咋办呢?还有就是英文大小写的场景,用户搜索"MAIN",那结果及时匹配到了“main”(小写的),这个单词是否应该高亮呢?也许这时候你会用业务代码实现toLowerCase下基于位置下标的匹配。 挺麻烦的吧,elasticsearch,自动可以返回高亮字段!并且可以自由指定高亮的html前后标签。 (4)实在太多了....这家伙天生为索引而生,而且版本还在不断地迭代。不差机器的话,用用吧! 4. 退而求其次 4.1 普通数据库 尽管elasticsearch在搜索场景下,是非常好用的利器!但是它比较消耗机器资源,如果你的数据规模并不大,而且想快速实现功能。你可以使用mysql或mongo来代替,完全没有问题。 技术是为了解决特定业务场景下的问题,结合当前手头的资源,适合自己的才是最好的。也许你搞了一个单机器的elasticsearch,单机器内存只有2G,它的表现并不会比mysql、mongo来的好。 当然,如果你为了使用上边提到的一些优秀的独有的特性,那elasticsearch一定还是最佳选择! 对于mysql(关系型数据库)和mongo(文档数据库)的区别这里不展开描述了,但对于搜索而言,两种都合适。有时候选型也不用很纠结,其实都是差不太多的东西,适合自己的、自己熟悉的、运维起来顺手的,就是最好的。 4.2 普通数据库实现中文分词搜索的原理 尽管mysql在5.7以后支持外挂第三方分词器,mongo在截止目前的版本中也不支持中文分词(你可能会看到一些文章中说可以指定language为chinese,但其实会报错的)。 其实当你选择普通数据库,你就不得不在逻辑代码中自己实现一套索引分词+搜索分词逻辑。 索引分词+搜索分词?为什么分开写,如果你有用过elasticsearch或solr,你会知道,在指定字段的时候,需要指定index分词器和search分词器。 下面以mongo为例做简要说明。 4.2.1 index分词器 意思是当数据“索引”截断如何分词。首先,这里必须要承认,数据之后存储了,才能被查询。在搜索中,这句话可以换成是“数据只有被索引了,才能被搜索”。 这时候请求打过来了,要索引一条数据,其中某字段是“今天我要吃冰激凌”,分词后得到“今天|我|要|吃|冰激凌”,这个就可以入库了。 如果你使用elasticsearch或solr,这个过程是自动的。如果你使用不支持外观分词器的常规数据库,这个过程你就要手动了,并把分词后的结果用空格分开(最好使用空格,因为西方语言的分词规则就是按空格拆分,以及逗号句号),存入数据库的一个待搜索的字段上。 效果如下图: 本站的其它博文中有介绍IKAnalyzer:https://www.52itw.com/java/6268.html 4.2.2 search分词器 当用户的查询请求打过来,用户输入了“好吃的冰激凌”,分词后得到“好吃|冰激凌”(“的”作为停用词stopwords,被自动忽略了,IKAnalyzer可以指定停用词表)。 于是这时候就回去上图的数据库表里面搜索“好吃 冰激凌”(与index分词器结果统一,还是用空格分隔)。 当然,对于mongo而言,你需要事先开启全文索引db.xxx.ensureIndex({content: "text"}),xxx是集合名,content是字段名,text是全文索引的标识。 mongo搜索的时候用这个语法:db.xxx.find( { $text: { $search: "好吃 冰激凌" } },{ score: { $meta: "textScore" } }).sort( { score: { $meta: "textScore" } } ) 4.2.3 索引库和存储库分开 为了减少单表的大小,为了让普通的列表查询、普通筛选可以跑的更快,你可以对原有的数据原封不动的做一张表。 然后对于搜索场景,再单独对需要被搜索的字段单独拎一张表出来! 然后二者之间做增量信号同步或定时差额同步,可能会有延迟,这个就看你能容忍多长时间(悄悄告诉你,elasticsearch也需要指定这个refresh时间,一般是1s到几秒、甚至分钟级。当然,二者的这个时间对饮的底层目的是不一样的)。 这样,搜索的时候先查询搜索库,拿到一个指针id的列表,然后拿到指针id的列表区存储里把数据一次性捞出来。当然,也是支持分页的,你查询搜索库其实也是普通的数据库查询嘛,支持分页参数的。 4.3 存储库和索引库的延伸阅读 很多有名的开源软件也是使用的存储库与索引库分离的技术方案,如apache atlas: apache atlas对于大数据领域的数据资产元数据管理、数据血缘上可谓是专家,也涉及资产搜索的特性,它的实现思路就是:从搜索库中做搜索、拿到key、再去存储库中做查询。 搜索库:上图右下角,可以看到使用的是elasticsearch、solr或lucene,多个选一个 存储库:上图左下角,可以看到使用的是Cassandra、HBase或BerkeleyDB,多个选一个 虽然apache atlas在只有搜索库或只有存储库的时候也可以很好的工作,但只针对于数据量并不大的场景。 搜索库,擅长搜索!存储库,擅长海量存储!搜索库多样化搜索,然后去存储库做点查。 当你的数据达到海量的时候,es+hbase也是一种很好的解决方案,不在这里展开说明了。
2024-01-27 17:49:04
537
admin-tim
转载文章
...然如何判断到底用哪个版本的 Greeting 问候方法合适呢?在进行这个之前,我们最好再定义一个枚举作为判断的依据: public enum Language{English, Chinese}public void GreetPeople(string name, Language lang){switch (lang){case Language.English:EnglishGreeting(name);break;case Language.Chinese:ChineseGreeting(name);break;} } OK,尽管这样解决了问题,但我不说大家也很容易想到,这个解决方案的可扩展性很差,如果日后我们需要再添加韩文版、日文版,就不得不反复修改枚举和GreetPeople() 方法,以适应新的需求。 在考虑新的解决方案之前,我们先看看 GreetPeople 的方法签名: public void GreetPeople(string name, Language lang); 我们仅看 string name,在这里,string 是参数类型,name 是参数变量,当我们赋给 name 字符串“Liker”时,它就代表“Liker”这个值;当我们赋给它“李志中”时,它又代表着“李志中”这个值。然后,我们可以在方法体内对这个 name 进行其他操作。哎,这简直是废话么,刚学程序就知道了。 如果你再仔细想想,假如 GreetPeople() 方法可以接受一个参数变量,这个变量可以代表另一个方法,当我们给这个变量赋值 EnglishGreeting 的时候,它代表着 EnglsihGreeting() 这个方法;当我们给它赋值ChineseGreeting 的时候,它又代表着 ChineseGreeting() 法。我们将这个参数变量命名为 MakeGreeting,那么不是可以如同给 name 赋值时一样,在调用 GreetPeople()方法的时候,给这个MakeGreeting 参数也赋上值么(ChineseGreeting 或者EnglsihGreeting 等)?然后,我们在方法体内,也可以像使用别的参数一样使用MakeGreeting。但是,由于 MakeGreeting 代表着一个方法,它的使用方式应该和它被赋的方法(比如ChineseGreeting)是一样的,比如:MakeGreeting(name); 好了,有了思路了,我们现在就来改改GreetPeople()方法,那么它应该是这个样子了: public void GreetPeople(string name, MakeGreeting) { MakeGreeting(name); } 注意到 ,这个位置通常放置的应该是参数的类型,但到目前为止,我们仅仅是想到应该有个可以代表方法的参数,并按这个思路去改写 GreetPeople 方法,现在就出现了一个大问题:这个代表着方法的 MakeGreeting 参数应该是什么类型的? 说明:这里已不再需要枚举了,因为在给MakeGreeting 赋值的时候动态地决定使用哪个方法,是 ChineseGreeting 还是 EnglishGreeting,而在这个两个方法内部,已经对使用“Good Morning”还是“早上好”作了区分。 聪明的你应该已经想到了,现在是委托该出场的时候了,但讲述委托之前,我们再看看MakeGreeting 参数所能代表的 ChineseGreeting()和EnglishGreeting()方法的签名: public void EnglishGreeting(string name) public void ChineseGreeting(string name) 如同 name 可以接受 String 类型的“true”和“1”,但不能接受bool 类型的true 和int 类型的1 一样。MakeGreeting 的参数类型定义应该能够确定 MakeGreeting 可以代表的方法种类,再进一步讲,就是 MakeGreeting 可以代表的方法的参数类型和返回类型。 于是,委托出现了:它定义了 MakeGreeting 参数所能代表的方法的种类,也就是 MakeGreeting 参数的类型。 本例中委托的定义: public delegate void GreetingDelegate(string name); 与上面 EnglishGreeting() 方法的签名对比一下,除了加入了delegate 关键字以外,其余的是不是完全一样?现在,让我们再次改动GreetPeople()方法,如下所示: public delegate void GreetingDelegate(string name);public void GreetPeople(string name, GreetingDelegate MakeGreeting){MakeGreeting(name);} 如你所见,委托 GreetingDelegate 出现的位置与 string 相同,string 是一个类型,那么 GreetingDelegate 应该也是一个类型,或者叫类(Class)。但是委托的声明方式和类却完全不同,这是怎么一回事?实际上,委托在编译的时候确实会编译成类。因为 Delegate 是一个类,所以在任何可以声明类的地方都可以声明委托。更多的内容将在下面讲述,现在,请看看这个范例的完整代码: public delegate void GreetingDelegate(string name);class Program{private static void EnglishGreeting(string name){Console.WriteLine("Good Morning, " + name);}private static void ChineseGreeting(string name){Console.WriteLine("早上好, " + name);}private static void GreetPeople(string name, GreetingDelegate MakeGreeting){MakeGreeting(name);}static void Main(string[] args){GreetPeople("Liker", EnglishGreeting);GreetPeople("李志中", ChineseGreeting);Console.ReadLine();} } 我们现在对委托做一个总结:委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If … Else(Switch)语句,同时使得程序具有更好的可扩展性。 1.1.2 将方法绑定到委托 看到这里,是不是有那么点如梦初醒的感觉?于是,你是不是在想:在上面的例子中,我不一定要直接在 GreetPeople() 方法中给 name 参数赋值,我可以像这样使用变量: static void Main(string[] args){GreetPeople("Liker", EnglishGreeting);GreetPeople("李志中", ChineseGreeting);Console.ReadLine();} 而既然委托 GreetingDelegate 和类型 string 的地位一样,都是定义了一种参数类型,那么,我是不是也可以这么使用委托? static void Main(string[] args){GreetingDelegate delegate1, delegate2;delegate1 = EnglishGreeting;delegate2 = ChineseGreeting;GreetPeople("Liker", delegate1);GreetPeople("李志中", delegate2);Console.ReadLine();} 如你所料,这样是没有问题的,程序一如预料的那样输出。这里,我想说的是委托不同于 string 的一个特性:可以将多个方法赋给同一个委托,或者叫将多个方法绑定到同一个委托,当调用这个委托的时候,将依次调用其所绑定的方法。在这个例子中,语法如下: static void Main(string[] args){GreetingDelegate delegate1;delegate1 = EnglishGreeting; delegate1 += ChineseGreeting;GreetPeople("Liker", delegate1);Console.ReadLine();} 实际上,我们可以也可以绕过GreetPeople 方法,通过委托来直接调用EnglishGreeting 和ChineseGreeting: static void Main(string[] args){GreetingDelegate delegate1;delegate1 = EnglishGreeting;delegate1 += ChineseGreeting; delegate1("Liker");Console.ReadLine();} 说明:这在本例中是没有问题的,但回头看下上面 GreetPeople() 的定义,在它之中可以做一些对于 EnglshihGreeting 和 ChineseGreeting 来说都需要进行的工作,为了简便我做了省略。 注意这里,第一次用的“=”,是赋值的语法;第二次,用的是“+=”,是绑定的语法。如果第一次就使用“+=”,将出现“使用了未赋值的局部变量”的编译错误。我们也可以使用下面的代码来这样简化这一过程: GreetingDelegate delegate1 = new GreetingDelegate(EnglishGreeting);delegate1 += ChineseGreeting; 既然给委托可以绑定一个方法,那么也应该有办法取消对方法的绑定,很容易想到,这个语法是“-=”: static void Main(string[] args){GreetingDelegate delegate1 = new GreetingDelegate(EnglishGreeting);delegate1 += ChineseGreeting;GreetPeople("Liker", delegate1);Console.WriteLine();delegate1 -= EnglishGreeting;GreetPeople("李志中", delegate1);Console.ReadLine();} 让我们再次对委托作个总结: 使用委托可以将多个方法绑定到同一个委托变量,当调用此变量时(这里用“调用”这个词,是因为此变量代表一个方法),可以依次调用所有绑定的方法。 1.2 事件的由来 1.2.1 更好的封装性 我们继续思考上面的程序:上面的三个方法都定义在 Programe 类中,这样做是为了理解的方便,实际应用中,通常都是 GreetPeople 在一个类中,ChineseGreeting 和 EnglishGreeting 在另外的类中。现在你已经对委托有了初步了解,是时候对上面的例子做个改进了。假设我们将 GreetingPeople() 放在一个叫 GreetingManager 的类中,那么新程序应该是这个样子的: namespace Delegate{public delegate void GreetingDelegate(string name);public class GreetingManager{public void GreetPeople(string name, GreetingDelegate MakeGreeting){MakeGreeting(name);} }class Program{private static void EnglishGreeting(string name){Console.WriteLine("Good Morning, " + name);}private static void ChineseGreeting(string name){Console.WriteLine("早上好, " + name);}static void Main(string[] args){GreetingManager gm = new GreetingManager();gm.GreetPeople("Liker", EnglishGreeting);gm.GreetPeople("李志中", ChineseGreeting);} }} 我们运行这段代码,嗯,没有任何问题。程序一如预料地那样输出了: // Good Morning, Liker 早上好, 李志中 // 现在,假设我们需要使用上一节学到的知识,将多个方法绑定到同一个委托变量,该如何做呢?让我们再次改写代码: static void Main(string[] args){GreetingManager gm = new GreetingManager();GreetingDelegate delegate1;delegate1 = EnglishGreeting;delegate1 += ChineseGreeting;gm.GreetPeople("Liker", delegate1);} 输出: Good Morning, Liker 早上好, Liker 到了这里,我们不禁想到:面向对象设计,讲究的是对象的封装,既然可以声明委托类型的变量(在上例中是delegate1),我们何不将这个变量封装到 GreetManager 类中?在这个类的客户端中使用不是更方便么?于是,我们改写GreetManager 类,像这样: public class GreetingManager{/// <summary>/// 在 GreetingManager 类的内部声明 delegate1 变量/// </summary>public GreetingDelegate delegate1;public void GreetPeople(string name, GreetingDelegate MakeGreeting){MakeGreeting(name);} } 现在,我们可以这样使用这个委托变量: static void Main(string[] args){GreetingManager gm = new GreetingManager();gm.delegate1 = EnglishGreeting;gm.delegate1 += ChineseGreeting;gm.GreetPeople("Liker", gm.delegate1);} 输出为: Good Morning, Liker 早上好, Liker 尽管这样做没有任何问题,但我们发现这条语句很奇怪。在调用gm.GreetPeople 方法的时候,再次传递了gm 的delegate1 字段, 既然如此,我们何不修改 GreetingManager 类成这样: public class GreetingManager{/// <summary>/// 在 GreetingManager 类的内部声明 delegate1 变量/// </summary>public GreetingDelegate delegate1;public void GreetPeople(string name){if (delegate1 != null) // 如果有方法注册委托变量{ delegate1(name); // 通过委托调用方法} }} 在客户端,调用看上去更简洁一些: static void Main(string[] args){GreetingManager gm = new GreetingManager();gm.delegate1 = EnglishGreeting;gm.delegate1 += ChineseGreeting;gm.GreetPeople("Liker"); //注意,这次不需要再传递 delegate1 变量} 尽管这样达到了我们要的效果,但是还是存在着问题:在这里,delegate1 和我们平时用的string 类型的变量没有什么分别,而我们知道,并不是所有的字段都应该声明成public,合适的做法是应该public 的时候public,应该private 的时候private。 我们先看看如果把 delegate1 声明为 private 会怎样?结果就是:这简直就是在搞笑。因为声明委托的目的就是为了把它暴露在类的客户端进行方法的注册,你把它声明为 private 了,客户端对它根本就不可见,那它还有什么用? 再看看把delegate1 声明为 public 会怎样?结果就是:在客户端可以对它进行随意的赋值等操作,严重破坏对象的封装性。 最后,第一个方法注册用“=”,是赋值语法,因为要进行实例化,第二个方法注册则用的是“+=”。但是,不管是赋值还是注册,都是将方法绑定到委托上,除了调用时先后顺序不同,再没有任何的分别,这样不是让人觉得很别扭么? 现在我们想想,如果delegate1 不是一个委托类型,而是一个string 类型,你会怎么做?答案是使用属性对字段进行封装。 于是,Event 出场了,它封装了委托类型的变量,使得:在类的内部,不管你声明它是public还是protected,它总是private 的。在类的外部,注册“+=”和注销“-=”的访问限定符与你在声明事件时使用的访问符相同。我们改写GreetingManager 类,它变成了这个样子: public class GreetingManager{//这一次我们在这里声明一个事件public event GreetingDelegate MakeGreet;public void GreetPeople(string name){MakeGreet(name);} } 很容易注意到:MakeGreet 事件的声明与之前委托变量 delegate1 的声明唯一的区别是多了一个 event 关键字。看到这里,在结合上面的讲解,你应该明白到:事件其实没什么不好理解的,声明一个事件不过类似于声明一个进行了封装的委托类型的变量而已。 为了证明上面的推论,如果我们像下面这样改写Main 方法: static void Main(string[] args){GreetingManager gm = new GreetingManager();gm.MakeGreet = EnglishGreeting; // 编译错误1gm.MakeGreet += ChineseGreeting;gm.GreetPeople("Liker");} 会得到编译错误: 1.2.2 限制类型能力 使用事件不仅能获得比委托更好的封装性以外,还能限制含有事件的类型的能力。这是什么意思呢?它的意思是说:事件应该由事件发布者触发,而不应该由事件的客户端(客户程序)来触发。请看下面的范例: using System;class Program{static void Main(string[] args){Publishser pub = new Publishser();Subscriber sub = new Subscriber();pub.NumberChanged += new NumberChangedEventHandler(sub.OnNumberChanged);pub.DoSomething(); // 应该通过DoSomething()来触发事件pub.NumberChanged(100); // 但可以被这样直接调用,对委托变量的不恰当使用} }/// <summary>/// 定义委托/// </summary>/// <param name="count"></param>public delegate void NumberChangedEventHandler(int count);/// <summary>/// 定义事件发布者/// </summary>public class Publishser{private int count;public NumberChangedEventHandler NumberChanged; // 声明委托变量//public event NumberChangedEventHandler NumberChanged; // 声明一个事件public void DoSomething(){// 在这里完成一些工作 ...if (NumberChanged != null) // 触发事件{ count++;NumberChanged(count);} }}/// <summary>/// 定义事件订阅者/// </summary>public class Subscriber{public void OnNumberChanged(int count){Console.WriteLine("Subscriber notified: count = {0}", count);} } 上面代码定义了一个NumberChangedEventHandler 委托,然后我们创建了事件的发布者Publisher 和订阅者Subscriber。当使用委托变量时,客户端可以直接通过委托变量触发事件,也就是直接调用pub.NumberChanged(100),这将会影响到所有注册了该委托的订阅者。而事件的本意应该为在事件发布者在其本身的某个行为中触发,比如说在方法DoSomething()中满足某个条件后触发。通过添加event 关键字来发布事件,事件发布者的封装性会更好,事件仅仅是供其他类型订阅,而客户端不能直接触发事件(语句pub.NumberChanged(100)无法通过编译),事件只能在事件发布者Publisher 类的内部触发(比如在方法pub.DoSomething()中),换言之,就是NumberChanged(100)语句只能在Publisher 内部被调用。大家可以尝试一下,将委托变量的声明那行代码注释掉,然后取消下面事件声明的注释。此时程序是无法编译的,当你使用了event 关键字之后,直接在客户端触发事件这种行为,也就是直接调用pub.NumberChanged(100),是被禁止的。事件只能通过调用DoSomething() 来触发。这样才是事件的本意,事件发布者的封装才会更好。 就好像如果我们要定义一个数字类型,我们会使用int 而不是使用object 一样,给予对象过多的能力并不见得是一件好事,应该是越合适越好。尽管直接使用委托变量通常不会有什么问题,但它给了客户端不应具有的能力,而使用事件,可以限制这一能力,更精确地对类型进行封装。 说 明:这里还有一个约定俗称的规定,就是订阅事件的方法的命名,通常为“On 事件名”,比如这里的OnNumberChanged。 1.3 委托的编译代码 这时候,我们注释掉编译错误的行,然后重新进行编译,再借助 Reflactor 来对 event 的声明语句做一探究,看看为什么会发生这样的错误: 可以看到,实际上尽管我们在GreetingManager 里将 MakeGreet 声明为public,但是,实际上MakeGreet 会被编译成私有字段,难怪会发生上面的编译错误了,因为它根本就不允许在GreetingManager 类的外面以赋值的方式访问,从而验证了我们上面所做的推论。 我们再进一步看下MakeGreet 所产生的代码: // private GreetingDelegate MakeGreet; //对事件的声明实际是声明一个私有的委托变量 [MethodImpl(MethodImplOptions.Synchronized)] public void add_MakeGreet(GreetingDelegate value) { this.MakeGreet = (GreetingDelegate) Delegate.Combine(this.MakeGreet, value); } [MethodImpl(MethodImplOptions.Synchronized)] public void remove_MakeGreet(GreetingDelegate value) { this.MakeGreet = (GreetingDelegate) Delegate.Remove(this.MakeGreet, value); } // 现在已经很明确了:MakeGreet 事件确实是一个GreetingDelegate 类型的委托,只不过不管是不是声明为public,它总是被声明为private。另外,它还有两个方法,分别是add_MakeGreet和remove_MakeGreet,这两个方法分别用于注册委托类型的方法和取消注册。实际上也就是:“+= ”对应 add_MakeGreet,“-=”对应remove_MakeGreet。而这两个方法的访问限制取决于声明事件时的访问限制符。 在add_MakeGreet()方法内部,实际上调用了System.Delegate 的Combine()静态方法,这个方法用于将当前的变量添加到委托链表中。 我们前面提到过两次,说委托实际上是一个类,在我们定义委托的时候: // public delegate void GreetingDelegate(string name); // 当编译器遇到这段代码的时候,会生成下面这样一个完整的类: // public class GreetingDelegate:System.MulticastDelegate { public GreetingDelegate(object @object, IntPtr method); public virtual IAsyncResult BeginInvoke(string name, AsyncCallback callback, object @object); public virtual void EndInvoke(IAsyncResult result); public virtual void Invoke(string name); } // 1.4 .NET 框架中的委托和事件 1.4.1 范例说明 上面的例子已不足以再进行下面的讲解了,我们来看一个新的范例,因为之前已经介绍了很多的内容,所以本节的进度会稍微快一些! 假设我们有个高档的热水器,我们给它通上电,当水温超过95 度的时候:1、扬声器会开始发出语音,告诉你水的温度;2、液晶屏也会改变水温的显示,来提示水已经快烧开了。 现在我们需要写个程序来模拟这个烧水的过程,我们将定义一个类来代表热水器,我们管它叫:Heater,它有代表水温的字段,叫做 temperature;当然,还有必不可少的给水加热方法 BoilWater(),一个发出语音警报的方法 MakeAlert(),一个显示水温的方法,ShowMsg()。 namespace Delegate{/// <summary>/// 热水器/// </summary>public class Heater{/// <summary>/// 水温/// </summary>private int temperature;/// <summary>/// 烧水/// </summary>public void BoilWater(){for (int i = 0; i <= 100; i++){temperature = i;if (temperature > 95){MakeAlert(temperature);ShowMsg(temperature);} }}/// <summary>/// 发出语音警报/// </summary>/// <param name="param"></param>private void MakeAlert(int param){Console.WriteLine("Alarm:嘀嘀嘀,水已经 {0} 度了:", param);}/// <summary>/// 显示水温/// </summary>/// <param name="param"></param>private void ShowMsg(int param){Console.WriteLine("Display:水快开了,当前温度:{0}度。", param);} }class Program{static void Main(){Heater ht = new Heater();ht.BoilWater();} }} 1.4.2 Observer 设计模式简介 上面的例子显然能完成我们之前描述的工作,但是却并不够好。现在假设热水器由三部分组成:热水器、警报器、显示器,它们来自于不同厂商并进行了组装。那么,应该是热水器仅仅负责烧水,它不能发出警报也不能显示水温;在水烧开时由警报器发出警报、显示器显示提示和水温。 这时候,上面的例子就应该变成这个样子: /// <summary>/// 热水器/// </summary>public class Heater{private int temperature; private void BoilWater(){for (int i = 0; i <= 100; i++){temperature = i;} }}/// <summary>/// 警报器/// </summary>public class Alarm{private void MakeAlert(int param){Console.WriteLine("Alarm:嘀嘀嘀,水已经 {0} 度了:", param);} }/// <summary>/// 显示器/// </summary>public class Display{private void ShowMsg(int param){Console.WriteLine("Display:水已烧开,当前温度:{0}度。", param);} } 这里就出现了一个问题:如何在水烧开的时候通知报警器和显示器? 在继续进行之前,我们先了解一下Observer 设计模式,Observer 设计模式中主要包括如下两类对象: Subject:监视对象,它往往包含着其他对象所感兴趣的内容。在本范例中,热水器就是一个监视对象,它包含的其他对象所感兴趣的内容,就是 temprature 字段,当这个字段的值快到100 时,会不断把数据发给监视它的对象。 Observer:监视者,它监视Subject,当 Subject 中的某件事发生的时候,会告知Observer,而Observer 则会采取相应的行动。在本范例中,Observer 有警报器和显示器,它们采取的行动分别是发出警报和显示水温。 在本例中,事情发生的顺序应该是这样的: 1. 警报器和显示器告诉热水器,它对它的温度比较感兴趣(注册)。 2. 热水器知道后保留对警报器和显示器的引用。 3. 热水器进行烧水这一动作,当水温超过 95 度时,通过对警报器和显示器的引用,自动调用警报器的MakeAlert()方法、显示器的ShowMsg()方法。 类似这样的例子是很多的,GOF 对它进行了抽象,称为 Observer 设计模式:Observer 设计模式是为了定义对象间的一种一对多的依赖关系,以便于当一个对象的状态改变时,其他依赖于它的对象会被自动告知并更新。Observer 模式是一种松耦合的设计模式。 1.4.3 实现范例的Observer 设计模式 我们之前已经对委托和事件介绍很多了,现在写代码应该很容易了,现在在这里直接给出代码,并在注释中加以说明。 namespace Delegate{public class Heater{private int temperature;public delegate void BoilHandler(int param);public event BoilHandler BoilEvent;public void BoilWater(){for (int i = 0; i <= 100; i++){temperature = i;if (temperature > 95){if (BoilEvent != null){ BoilEvent(temperature); // 调用所有注册对象的方法} }} }}public class Alarm{public void MakeAlert(int param){Console.WriteLine("Alarm:嘀嘀嘀,水已经 {0} 度了:", param);} }public class Display{public static void ShowMsg(int param) // 静态方法{ Console.WriteLine("Display:水快烧开了,当前温度:{0}度。", param);} }class Program{static void Main(){Heater heater = new Heater();Alarm alarm = new Alarm();heater.BoilEvent += alarm.MakeAlert; // 注册方法heater.BoilEvent += (new Alarm()).MakeAlert; // 给匿名对象注册方法heater.BoilEvent += Display.ShowMsg; // 注册静态方法heater.BoilWater(); // 烧水,会自动调用注册过对象的方法} }} 输出为: // Alarm:嘀嘀嘀,水已经 96 度了: Alarm:嘀嘀嘀,水已经 96 度了: Display:水快烧开了,当前温度:96 度。 // 省略... // 1.4.4 .NET 框架中的委托与事件 尽管上面的范例很好地完成了我们想要完成的工作,但是我们不仅疑惑:为什么.NET Framework 中的事件模型和上面的不同?为什么有很多的EventArgs 参数? 在回答上面的问题之前,我们先搞懂 .NET Framework 的编码规范: 1. 委托类型的名称都应该以 EventHandler 结束。 2. 委托的原型定义:有一个void 返回值,并接受两个输入参数:一个Object 类型,一个EventArgs 类型(或继承自EventArgs)。 3. 事件的命名为委托去掉 EventHandler 之后剩余的部分。 4. 继承自 EventArgs 的类型应该以EventArgs 结尾。 再做一下说明: 1. 委托声明原型中的Object 类型的参数代表了Subject,也就是监视对象,在本例中是Heater(热水器)。回调函数(比如Alarm 的MakeAlert)可以通过它访问触发事件的对象(Heater)。 2. EventArgs 对象包含了Observer 所感兴趣的数据,在本例中是temperature。 上面这些其实不仅仅是为了编码规范而已,这样也使得程序有更大的灵活性。比如说,如果我们不光想获得热水器的温度,还想在Observer 端(警报器或者显示器)方法中获得它的生产日期、型号、价格,那么委托和方法的声明都会变得很麻烦,而如果我们将热水器的引用传给警报器的方法,就可以在方法中直接访问热水器了。 现在我们改写之前的范例,让它符合.NET Framework的规范: using System;using System.Collections.Generic;using System.Text;namespace Delegate{public class Heater{private int temperature;public string type = "RealFire 001"; // 添加型号作为演示public string area = "China Xian"; // 添加产地作为演示public delegate void BoiledEventHandler(Object sender, BoiledEventArgs e);public event BoiledEventHandler Boiled; // 声明事件// 定义 BoiledEventArgs 类,传递给 Observer 所感兴趣的信息public class BoiledEventArgs : EventArgs{public readonly int temperature;public BoiledEventArgs(int temperature){this.temperature = temperature;} }// 可以供继承自 Heater 的类重写,以便继承类拒绝其他对象对它的监视protected virtual void OnBoiled(BoiledEventArgs e){if (Boiled != null){Boiled(this, e); // 调用所有注册对象的方法} }public void BoilWater(){for (int i = 0; i <= 100; i++){temperature = i;if (temperature > 95){// 建立BoiledEventArgs 对象。BoiledEventArgs e = new BoiledEventArgs(temperature);OnBoiled(e); // 调用 OnBolied 方法} }}public class Alarm{public void MakeAlert(Object sender, Heater.BoiledEventArgs e){Heater heater = (Heater)sender; // 这里是不是很熟悉呢?// 访问 sender 中的公共字段Console.WriteLine("Alarm:{0} - {1}: ", heater.area, heater.type);Console.WriteLine("Alarm: 嘀嘀嘀,水已经 {0} 度了:", e.temperature);Console.WriteLine();} }public class Display{public static void ShowMsg(Object sender, Heater.BoiledEventArgs e) // 静态方法{Heater heater = (Heater)sender;Console.WriteLine("Display:{0} - {1}: ", heater.area, heater.type);Console.WriteLine("Display:水快烧开了,当前温度:{0}度。", e.temperature);Console.WriteLine();} }class Program{static void Main(){Heater heater = new Heater();Alarm alarm = new Alarm();heater.Boiled += alarm.MakeAlert; //注册方法heater.Boiled += (new Alarm()).MakeAlert; //给匿名对象注册方法heater.Boiled += new Heater.BoiledEventHandler(alarm.MakeAlert); //也可以这么注册heater.Boiled += Display.ShowMsg; //注册静态方法heater.BoilWater(); //烧水,会自动调用注册过对象的方法} }} } 输出为: Alarm:China Xian - RealFire 001: Alarm: 嘀嘀嘀,水已经 96 度了: Alarm:China Xian - RealFire 001: Alarm: 嘀嘀嘀,水已经 96 度了: Alarm:China Xian - RealFire 001: Alarm: 嘀嘀嘀,水已经 96 度了: Display:China Xian - RealFire 001: Display:水快烧开了,当前温度:96 度。 // 省略 ... 1.5 委托进阶 1.5.1 为什么委托定义的返回值通常都为 void ? 尽管并非必需,但是我们发现很多的委托定义返回值都为 void,为什么呢?这是因为委托变量可以供多个订阅者注册,如果定义了返回值,那么多个订阅者的方法都会向发布者返回数值,结果就是后面一个返回的方法值将前面的返回值覆盖掉了,因此,实际上只能获得最后一个方法调用的返回值。可以运行下面的代码测试一下。除此以外,发布者和订阅者是松耦合的,发布者根本不关心谁订阅了它的事件、为什么要订阅,更别说订阅者的返回值了,所以返回订阅者的方法返回值大多数情况下根本没有必要。 1.5.2 如何让事件只允许一个客户订阅? 少数情况下,比如像上面,为了避免发生“值覆盖”的情况(更多是在异步调用方法时,后面会讨论),我们可能想限制只允许一个客户端注册。此时怎么做呢?我们可以向下面这样,将事件声明为private 的,然后提供两个方法来进行注册和取消注册: public class Publishser{private event GeneralEventHandler NumberChanged; // 声明一个私有事件// 注册事件public void Register(GeneralEventHandler method){NumberChanged = method;}// 取消注册public void UnRegister(GeneralEventHandler method){NumberChanged -= method;}public void DoSomething(){// 做某些其余的事情if (NumberChanged != null){ // 触发事件string rtn = NumberChanged();Console.WriteLine("Return: {0}", rtn); // 打印返回的字符串,输出为Subscriber3} }} 注意上面,在UnRegister()中,没有进行任何判断就使用了NumberChanged -= method 语句。这是因为即使method 方法没有进行过注册,此行语句也不会有任何问题,不会抛出异常,仅仅是不会产生任何效果而已。 注意在Register()方法中,我们使用了赋值操作符“=”,而非“+=”,通过这种方式就避免了多个方法注册。 1.7 委托和方法的异步调用 通常情况下,如果需要异步执行一个耗时的操作,我们会新起一个线程,然后让这个线程去执行代码。但是对于每一个异步调用都通过创建线程来进行操作显然会对性能产生一定的影响,同时操作也相对繁琐一些。.NET 中可以通过委托进行方法的异步调用,就是说客户端在异步调用方法时,本身并不会因为方法的调用而中断,而是从线程池中抓取一个线程去执行该方法,自身线程(主线程)在完成抓取线程这一过程之后,继续执行下面的代码,这样就实现了代码的并行执行。使用线程池的好处就是避免了频繁进行异步调用时创建、销毁线程的开销。当我们在委托对象上调用BeginInvoke()时,便进行了一个异步的方法调用。 事件发布者和订阅者之间往往是松耦合的,发布者通常不需要获得订阅者方法执行的情况;而当使用异步调用时,更多情况下是为了提升系统的性能,而并非专用于事件的发布和订阅这一编程模型。而在这种情况下使用异步编程时,就需要进行更多的控制,比如当异步执行方法的方法结束时通知客户端、返回异步执行方法的返回值等。本节就对 BeginInvoke() 方法、EndInvoke() 方法和其相关的 IAysncResult 做一个简单的介绍。 我们先看这样一段代码,它演示了不使用异步调用的通常情况: class Program7{static void Main(string[] args){Console.WriteLine("Client application started!\n");Thread.CurrentThread.Name = "Main Thread";Calculator cal = new Calculator();int result = cal.Add(2, 5);Console.WriteLine("Result: {0}\n", result);// 做某些其它的事情,模拟需要执行3 秒钟for (int i = 1; i <= 3; i++){Thread.Sleep(TimeSpan.FromSeconds(i));Console.WriteLine("{0}: Client executed {1} second(s).", Thread.CurrentThread.Name, i);}Console.WriteLine("\nPress any key to exit...");Console.ReadLine();} }public class Calculator{public int Add(int x, int y){if (Thread.CurrentThread.IsThreadPoolThread){Thread.CurrentThread.Name = "Pool Thread";}Console.WriteLine("Method invoked!");// 执行某些事情,模拟需要执行2 秒钟for (int i = 1; i <= 2; i++){Thread.Sleep(TimeSpan.FromSeconds(i));Console.WriteLine("{0}: Add executed {1} second(s).", Thread.CurrentThread.Name, i);}Console.WriteLine("Method complete!");return x + y;} } 上面代码有几个关于对于线程的操作,如果不了解可以看一下下面的说明,如果你已经了解可以直接跳过: 1. Thread.Sleep(),它会让执行当前代码的线程暂停一段时间(如果你对线程的概念比较陌生,可以理解为使程序的执行暂停一段时间),以毫秒为单位,比如Thread.Sleep(1000),将会使线程暂停1 秒钟。在上面我使用了它的重载方法,个人觉得使用TimeSpan.FromSeconds(1),可读性更好一些。 2. Thread.CurrentThread.Name,通过这个属性可以设置、获取执行当前代码的线程的名称,值得注意的是这个属性只可以设置一次,如果设置两次,会抛出异常。 3. Thread.IsThreadPoolThread,可以判断执行当前代码的线程是否为线程池中的线程。 通过这几个方法和属性,有助于我们更好地调试异步调用方法。上面代码中除了加入了一些对线程的操作以外再没有什么特别之处。我们建了一个Calculator 类,它只有一个Add 方法,我们模拟了这个方法需要执行2 秒钟时间,并且每隔一秒进行一次输出。而在客户端程序中,我们使用result 变量保存了方法的返回值并进行了打印。随后,我们再次模拟了客户端程序接下来的操作需要执行2 秒钟时间。运行这段程序,会产生下面的输出: // Client application started! Method invoked! Main Thread: Add executed 1 second(s). Main Thread: Add executed 2 second(s). Method complete! Result: 7 Main Thread: Client executed 1 second(s). Main Thread: Client executed 2 second(s). Main Thread: Client executed 3 second(s). Press any key to exit... // 如果你确实执行了这段代码,会看到这些输出并不是一瞬间输出的,而是执行了大概5 秒钟的时间,因为线程是串行执行的,所以在执行完 Add() 方法之后才会继续客户端剩下的代码。 接下来我们定义一个AddDelegate 委托,并使用BeginInvoke()方法来异步地调用它。在上面已经介绍过,BeginInvoke()除了最后两个参数为AsyncCallback 类型和Object 类型以外,前面的参数类型和个数与委托定义相同。另外BeginInvoke()方法返回了一个实现了IAsyncResult 接口的对象(实际上就是一个AsyncResult 类型实例,注意这里IAsyncResult 和AysncResult 是不同的,它们均包含在.NET Framework 中)。 AsyncResult 的用途有这么几个:传递参数,它包含了对调用了BeginInvoke()的委托的引用;它还包含了BeginInvoke()的最后一个Object 类型的参数;它可以鉴别出是哪个方法的哪一次调用,因为通过同一个委托变量可以对同一个方法调用多次。 EndInvoke()方法接受IAsyncResult 类型的对象(以及ref 和out 类型参数,这里不讨论了,对它们的处理和返回值类似),所以在调用BeginInvoke()之后,我们需要保留IAsyncResult,以便在调用EndInvoke()时进行传递。这里最重要的就是EndInvoke()方法的返回值,它就是方法的返回值。除此以外,当客户端调用EndInvoke()时,如果异步调用的方法没有执行完毕,则会中断当前线程而去等待该方法,只有当异步方法执行完毕后才会继续执行后面的代码。所以在调用完BeginInvoke()后立即执行EndInvoke()是没有任何意义的。我们通常在尽可能早的时候调用BeginInvoke(),然后在需要方法的返回值的时候再去调用EndInvoke(),或者是根据情况在晚些时候调用。说了这么多,我们现在看一下使用异步调用改写后上面的代码吧: using System.Threading;using System;public delegate int AddDelegate(int x, int y);class Program8{static void Main(string[] args){Console.WriteLine("Client application started!\n");Thread.CurrentThread.Name = "Main Thread";Calculator cal = new Calculator();AddDelegate del = new AddDelegate(cal.Add);IAsyncResult asyncResult = del.BeginInvoke(2, 5, null, null); // 异步调用方法// 做某些其它的事情,模拟需要执行3 秒钟for (int i = 1; i <= 3; i++){Thread.Sleep(TimeSpan.FromSeconds(i));Console.WriteLine("{0}: Client executed {1} second(s).", Thread.CurrentThread.Name, i);}int rtn = del.EndInvoke(asyncResult);Console.WriteLine("Result: {0}\n", rtn);Console.WriteLine("\nPress any key to exit...");Console.ReadLine();} }public class Calculator{public int Add(int x, int y){if (Thread.CurrentThread.IsThreadPoolThread){Thread.CurrentThread.Name = "Pool Thread";}Console.WriteLine("Method invoked!");// 执行某些事情,模拟需要执行2 秒钟for (int i = 1; i <= 2; i++){Thread.Sleep(TimeSpan.FromSeconds(i));Console.WriteLine("{0}: Add executed {1} second(s).", Thread.CurrentThread.Name, i);}Console.WriteLine("Method complete!");return x + y;} } 此时的输出为: // Client application started! Method invoked! Main Thread: Client executed 1 second(s). Pool Thread: Add executed 1 second(s). Main Thread: Client executed 2 second(s). Pool Thread: Add executed 2 second(s). Method complete! Main Thread: Client executed 3 second(s). Result: 7 Press any key to exit... // 现在执行完这段代码只需要3 秒钟时间,两个for 循环所产生的输出交替进行,这也说明了这两段代码并行执行的情况。可以看到Add() 方法是由线程池中的线程在执行, 因为Thread.CurrentThread.IsThreadPoolThread 返回了True,同时我们对该线程命名为了Pool Thread。另外我们可以看到通过EndInvoke()方法得到了返回值。有时候,我们可能会将获得返回值的操作放到另一段代码或者客户端去执行,而不是向上面那样直接写在BeginInvoke()的后面。比如说我们在Program 中新建一个方法GetReturn(),此时可以通过AsyncResult 的AsyncDelegate 获得del 委托对象,然后再在其上调用EndInvoke()方法,这也说明了AsyncResult 可以唯一的获取到与它相关的调用了的方法(或者也可以理解成委托对象)。所以上面获取返回值的代码也可以改写成这样: private static int GetReturn(IAsyncResult asyncResult){AsyncResult result = (AsyncResult)asyncResult;AddDelegate del = (AddDelegate)result.AsyncDelegate;int rtn = del.EndInvoke(asyncResult);return rtn;} 然后再将int rtn = del.EndInvoke(asyncResult);语句改为int rtn = GetReturn(asyncResult);。注意上面IAsyncResult 要转换为实际的类型AsyncResult 才能访问AsyncDelegate 属性,因为它没有包含在IAsyncResult 接口的定义中。 BeginInvoke 的另外两个参数分别是AsyncCallback 和Object 类型,其中AsyncCallback 是一个委托类型,它用于方法的回调,即是说当异步方法执行完毕时自动进行调用的方法。它的定义为: // public delegate void AsyncCallback(IAsyncResult ar); // Object 类型用于传递任何你想要的数值,它可以通过IAsyncResult 的AsyncState 属性获得。下面我们将获取方法返回值、打印返回值的操作放到了OnAddComplete()回调方法中: using System.Threading;using System;using System.Runtime.Remoting.Messaging;public delegate int AddDelegate(int x, int y);class Program9{static void Main(string[] args){Console.WriteLine("Client application started!\n");Thread.CurrentThread.Name = "Main Thread";Calculator cal = new Calculator();AddDelegate del = new AddDelegate(cal.Add);string data = "Any data you want to pass.";AsyncCallback callBack = new AsyncCallback(OnAddComplete);del.BeginInvoke(2, 5, callBack, data); // 异步调用方法// 做某些其它的事情,模拟需要执行3 秒钟for (int i = 1; i <= 3; i++){Thread.Sleep(TimeSpan.FromSeconds(i));Console.WriteLine("{0}: Client executed {1} second(s).", Thread.CurrentThread.Name, i);}Console.WriteLine("\nPress any key to exit...");Console.ReadLine();}static void OnAddComplete(IAsyncResult asyncResult){AsyncResult result = (AsyncResult)asyncResult;AddDelegate del = (AddDelegate)result.AsyncDelegate;string data = (string)asyncResult.AsyncState;int rtn = del.EndInvoke(asyncResult);Console.WriteLine("{0}: Result, {1}; Data: {2}\n", Thread.CurrentThread.Name, rtn, data);} }public class Calculator{public int Add(int x, int y){if (Thread.CurrentThread.IsThreadPoolThread){Thread.CurrentThread.Name = "Pool Thread";}Console.WriteLine("Method invoked!");// 执行某些事情,模拟需要执行2 秒钟for (int i = 1; i <= 2; i++){Thread.Sleep(TimeSpan.FromSeconds(i));Console.WriteLine("{0}: Add executed {1} second(s).", Thread.CurrentThread.Name, i);}Console.WriteLine("Method complete!");return x + y;} } 它产生的输出为: Client application started! Method invoked! Main Thread: Client executed 1 second(s). Pool Thread: Add executed 1 second(s). Main Thread: Client executed 2 second(s). Pool Thread: Add executed 2 second(s). Method complete! Pool Thread: Result, 7; Data: Any data you want to pass. Main Thread: Client executed 3 second(s). Press any key to exit... 这里有几个值得注意的地方: 1、我们在调用BeginInvoke()后不再需要保存IAysncResult 了,因为AysncCallback 委托将该对象定义在了回调方法的参数列表中; 2、我们在OnAddComplete()方法中获得了调用BeginInvoke()时最后一个参数传递的值,字符串“Any data you want to pass”; 3、执行回调方法的线程并非客户端线程Main Thread,而是来自线程池中的线程Pool Thread。另外如前面所说,在调用EndInvoke()时有可能会抛出异常,所以在应该将它放到try/catch 块中,这里就不再示范了。 1.8 总结 我们详细地讨论了C中的委托和事件,包括什么是委托、为什么要使用委托、事件的由来、.NET Framework 中的委托和事件、委托中方法异常和超时的处理、委托与异步编程、委托和事件对Observer 设计模式的意义。拥有了本章的知识,相信你以后遇到委托和事件时,将不会再有所畏惧。 本篇文章为转载内容。原文链接:https://blog.csdn.net/beyonddeg/article/details/53528482。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-05 16:02:19
80
转载
转载文章
...用正则表达式进行一些匹配处理。 对进入数据库的特殊字符(’,",\,<,>,&,,; 等)进行转义处理,或编码转换。基本上所有的后端语言都有对字符串进行转义处理的方法,比如 lodash 的 lodash._escapehtmlchar 库。 所有的查询语句建议使用数据库提供的参数化查询接口,参数化的语句使用参数而不是将用户输入变量嵌入到 SQL 语句中,即不要直接拼接 SQL 语句。例如 Node.js 中的 mysqljs 库的 query 方法中的 ? 占位参数。 mysql.query(SELECT FROM user WHERE username = ? AND psw = ?, [username, psw]); 在应用发布之前建议使用专业的 SQL 注入检测工具进行检测,以及时修补被发现的 SQL 注入漏洞。网上有很多这方面的开源工具,例如 sqlmap、SQLninja 等。 避免网站打印出 SQL 错误信息,比如类型错误、字段不匹配等,把代码里的 SQL 语句暴露出来,以防止攻击者利用这些错误信息进行 SQL 注入。 不要过于细化返回的错误信息,如果目的是方便调试,就去使用后端日志,不要在接口上过多的暴露出错信息,毕竟真正的用户不关心太多的技术细节,只要话术合理就行。 碰到要操作的数据库的代码,一定要慎重,小心使得万年船,多找几个人多来几次 code review,将问题都暴露出来,而且要善于利用工具,操作数据库相关的代码属于机密,没事不要去各种论坛晒自家站点的 SQL 语句,万一被人盯上了呢? 命令行注入 命令行注入漏洞,指的是攻击者能够通过 HTTP 请求直接侵入主机,执行攻击者预设的 shell 命令,听起来好像匪夷所思,这往往是 Web 开发者最容易忽视但是却是最危险的一个漏洞之一,看一个实例: 假如现在需要实现一个需求:用户提交一些内容到服务器,然后在服务器执行一些系统命令去产出一个结果返回给用户,接口的部分实现如下: // 以 Node.js 为例,假如在接口中需要从 github 下载用户指定的 repoconst exec = require('mz/child_process').exec;let params = {/ 用户输入的参数 /};exec(git clone ${params.repo} /some/path); 这段代码确实能够满足业务需求,正常的用户也确实能从指定的 git repo 上下载到想要的代码,可是和 SQL 注入一样,这段代码在恶意攻击者眼中,简直就是香饽饽。 如果 params.repo 传入的是 https://github.com/zoumiaojiang/zoumiaojiang.github.io.git 当然没问题了。 可是如果 params.repo 传入的是 https://github.com/xx/xx.git && rm -rf / && 恰好你的服务是用 root 权限起的就惨了。 具体恶意攻击者能用命令行注入干什么也像 SQL 注入一样,手法是千变万化的,比如「反弹 shell 注入」等,但原理都是一样的,我们绝对有能力防止命令行注入发生。防止命令行注入需要做到以下几件事情: 后端对前端提交内容需要完全选择不相信,并且对其进行规则限制(比如正则表达式)。 在调用系统命令前对所有传入参数进行命令行参数转义过滤。 不要直接拼接命令语句,借助一些工具做拼接、转义预处理,例如 Node.js 的 shell-escape npm 包。 还是前面的例子,我们可以做到如下: const exec = require('mz/child_process').exec;// 借助 shell-escape npm 包解决参数转义过滤问题const shellescape = require('shell-escape');let params = {/ 用户输入的参数 /};// 先过滤一下参数,让参数符合预期if (!/正确的表达式/.test(params.repo)) {return;}let cmd = shellescape(['git','clone',params.repo,'/some/path']);// cmd 的值: git clone 'https://github.com/xx/xx.git && rm -rf / &&' /some/path// 这样就不会被注入成功了。exec(cmd); DDoS 攻击 DDoS 又叫分布式拒绝服务,全称 Distributed Denial of Service,其原理就是利用大量的请求造成资源过载,导致服务不可用,这个攻击应该不能算是安全问题,这应该算是一个另类的存在,因为这种攻击根本就是耍流氓的存在,「伤敌一千,自损八百」的行为。出于保护 Web App 不受攻击的攻防角度,还是介绍一下 DDoS 攻击吧,毕竟也是挺常见的。 DDoS 攻击可以理解为:「你开了一家店,隔壁家点看不惯,就雇了一大堆黑社会人员进你店里干坐着,也不消费,其他客人也进不来,导致你营业惨淡」。为啥说 DDoS 是个「伤敌一千,自损八百」的行为呢?毕竟隔壁店还是花了不少钱雇黑社会但是啥也没得到不是?DDoS 攻击的目的基本上就以下几个: 深仇大恨,就是要干死你 敲诈你,不给钱就干你 忽悠你,不买我防火墙服务就会有“人”继续干你 也许你的站点遭受过 DDoS 攻击,具体什么原因怎么解读见仁见智。DDos 攻击从层次上可分为网络层攻击与应用层攻击,从攻击手法上可分为快型流量攻击与慢型流量攻击,但其原理都是造成资源过载,导致服务不可用。 网络层 DDoS 网络层 DDos 攻击包括 SYN Flood、ACK Flood、UDP Flood、ICMP Flood 等。 SYN Flood 攻击 SYN flood 攻击主要利用了 TCP 三次握手过程中的 Bug,我们都知道 TCP 三次握手过程是要建立连接的双方发送 SYN,SYN + ACK,ACK 数据包,而当攻击方随意构造源 IP 去发送 SYN 包时,服务器返回的 SYN + ACK 就不能得到应答(因为 IP 是随意构造的),此时服务器就会尝试重新发送,并且会有至少 30s 的等待时间,导致资源饱和服务不可用,此攻击属于慢型 DDoS 攻击。 ACK Flood 攻击 ACK Flood 攻击是在 TCP 连接建立之后,所有的数据传输 TCP 报文都是带有 ACK 标志位的,主机在接收到一个带有 ACK 标志位的数据包的时候,需要检查该数据包所表示的连接四元组是否存在,如果存在则检查该数据包所表示的状态是否合法,然后再向应用层传递该数据包。如果在检查中发现该数据包不合法,例如该数据包所指向的目的端口在本机并未开放,则主机操作系统协议栈会回应 RST 包告诉对方此端口不存在。 UDP Flood 攻击 UDP flood 攻击是由于 UDP 是一种无连接的协议,因此攻击者可以伪造大量的源 IP 地址去发送 UDP 包,此种攻击属于大流量攻击。正常应用情况下,UDP 包双向流量会基本相等,因此发起这种攻击的攻击者在消耗对方资源的时候也在消耗自己的资源。 ICMP Flood 攻击 ICMP Flood 攻击属于大流量攻击,其原理就是不断发送不正常的 ICMP 包(所谓不正常就是 ICMP 包内容很大),导致目标带宽被占用,但其本身资源也会被消耗。目前很多服务器都是禁 ping 的(在防火墙在可以屏蔽 ICMP 包),因此这种攻击方式已经落伍。 网络层 DDoS 防御 网络层的 DDoS 攻击究其本质其实是无法防御的,我们能做得就是不断优化服务本身部署的网络架构,以及提升网络带宽。当然,还是做好以下几件事也是有助于缓解网络层 DDoS 攻击的冲击: 网络架构上做好优化,采用负载均衡分流。 确保服务器的系统文件是最新的版本,并及时更新系统补丁。 添加抗 DDos 设备,进行流量清洗。 限制同时打开的 SYN 半连接数目,缩短 SYN 半连接的 Timeout 时间。 限制单 IP 请求频率。 防火墙等防护设置禁止 ICMP 包等。 严格限制对外开放的服务器的向外访问。 运行端口映射程序或端口扫描程序,要认真检查特权端口和非特权端口。 关闭不必要的服务。 认真检查网络设备和主机/服务器系统的日志。只要日志出现漏洞或是时间变更,那这台机器就可能遭到了攻击。 限制在防火墙外与网络文件共享。这样会给黑客截取系统文件的机会,主机的信息暴露给黑客,无疑是给了对方入侵的机会。 加钱堆机器。。 报警。。 应用层 DDoS 应用层 DDoS 攻击不是发生在网络层,是发生在 TCP 建立握手成功之后,应用程序处理请求的时候,现在很多常见的 DDoS 攻击都是应用层攻击。应用层攻击千变万化,目的就是在网络应用层耗尽你的带宽,下面列出集中典型的攻击类型。 CC 攻击 当时绿盟为了防御 DDoS 攻击研发了一款叫做 Collapasar 的产品,能够有效的防御 SYN Flood 攻击。黑客为了挑衅,研发了一款 Challenge Collapasar 攻击工具(简称 CC)。 CC 攻击的原理,就是针对消耗资源比较大的页面不断发起不正常的请求,导致资源耗尽。因此在发送 CC 攻击前,我们需要寻找加载比较慢,消耗资源比较多的网页,比如需要查询数据库的页面、读写硬盘文件的等。通过 CC 攻击,使用爬虫对某些加载需要消耗大量资源的页面发起 HTTP 请求。 DNS Flood DNS Flood 攻击采用的方法是向被攻击的服务器发送大量的域名解析请求,通常请求解析的域名是随机生成或者是网络世界上根本不存在的域名,被攻击的DNS 服务器在接收到域名解析请求的时候首先会在服务器上查找是否有对应的缓存,如果查找不到并且该域名无法直接由服务器解析的时候,DNS 服务器会向其上层 DNS 服务器递归查询域名信息。域名解析的过程给服务器带来了很大的负载,每秒钟域名解析请求超过一定的数量就会造成 DNS 服务器解析域名超时。 根据微软的统计数据,一台 DNS 服务器所能承受的动态域名查询的上限是每秒钟 9000 个请求。而我们知道,在一台 P3 的 PC 机上可以轻易地构造出每秒钟几万个域名解析请求,足以使一台硬件配置极高的 DNS 服务器瘫痪,由此可见 DNS 服务器的脆弱性。 HTTP 慢速连接攻击 针对 HTTP 协议,先建立起 HTTP 连接,设置一个较大的 Conetnt-Length,每次只发送很少的字节,让服务器一直以为 HTTP 头部没有传输完成,这样连接一多就很快会出现连接耗尽。 应用层 DDoS 防御 判断 User-Agent 字段(不可靠,因为可以随意构造) 针对 IP + cookie,限制访问频率(由于 cookie 可以更改,IP 可以使用代理,或者肉鸡,也不可靠) 关闭服务器最大连接数等,合理配置中间件,缓解 DDoS 攻击。 请求中添加验证码,比如请求中有数据库操作的时候。 编写代码时,尽量实现优化,并合理使用缓存技术,减少数据库的读取操作。 加钱堆机器。。 报警。。 应用层的防御有时比网络层的更难,因为导致应用层被 DDoS 攻击的因素非常多,有时往往是因为程序员的失误,导致某个页面加载需要消耗大量资源,有时是因为中间件配置不当等等。而应用层 DDoS 防御的核心就是区分人与机器(爬虫),因为大量的请求不可能是人为的,肯定是机器构造的。因此如果能有效的区分人与爬虫行为,则可以很好地防御此攻击。 其他 DDoS 攻击 发起 DDoS 也是需要大量的带宽资源的,但是互联网就像森林,林子大了什么鸟都有,DDoS 攻击者也能找到其他的方式发起廉价并且极具杀伤力的 DDoS 攻击。 利用 XSS 举个例子,如果 12306 页面有一个 XSS 持久型漏洞被恶意攻击者发现,只需在春节抢票期间在这个漏洞中执行脚本使得往某一个小站点随便发点什么请求,然后随着用户访问的增多,感染用户增多,被攻击的站点自然就会迅速瘫痪了。这种 DDoS 简直就是无本万利,不用惊讶,现在大站有 XSS 漏洞的不要太多。 来自 P2P 网络攻击 大家都知道,互联网上的 P2P 用户和流量都是一个极为庞大的数字。如果他们都去一个指定的地方下载数据,成千上万的真实 IP 地址连接过来,没有哪个设备能够支撑住。拿 BT 下载来说,伪造一些热门视频的种子,发布到搜索引擎,就足以骗到许多用户和流量了,但是这只是基础攻击。 高级的 P2P 攻击,是直接欺骗资源管理服务器。如迅雷客户端会把自己发现的资源上传到资源管理服务器,然后推送给其它需要下载相同资源的用户,这样,一个链接就发布出去。通过协议逆向,攻击者伪造出大批量的热门资源信息通过资源管理中心分发出去,瞬间就可以传遍整个 P2P 网络。更为恐怖的是,这种攻击是无法停止的,即使是攻击者自身也无法停止,攻击一直持续到 P2P 官方发现问题更新服务器且下载用户重启下载软件为止。 最后总结下,DDoS 不可能防的住,就好比你的店只能容纳 50 人,黑社会有 100 人,你就换一家大店,能容纳 500 人,然后黑社会又找来了 1000 人,这种堆人头的做法就是 DDoS 本质上的攻防之道,「道高一尺,魔高一丈,魔高一尺,道高一丈」,讲真,必要的时候就答应勒索你的人的条件吧,实在不行就报警吧。 流量劫持 流量劫持应该算是黑产行业的一大经济支柱了吧?简直是让人恶心到吐,不吐槽了,还是继续谈干货吧,流量劫持基本分两种:DNS 劫持 和 HTTP 劫持,目的都是一样的,就是当用户访问 zoumiaojiang.com 的时候,给你展示的并不是或者不完全是 zoumiaojiang.com 提供的 “内容”。 DNS 劫持 DNS 劫持,也叫做域名劫持,可以这么理解,「你打了一辆车想去商场吃饭,结果你打的车是小作坊派来的,直接给你拉到小作坊去了」,DNS 的作用是把网络地址域名对应到真实的计算机能够识别的 IP 地址,以便计算机能够进一步通信,传递网址和内容等。如果当用户通过某一个域名访问一个站点的时候,被篡改的 DNS 服务器返回的是一个恶意的钓鱼站点的 IP,用户就被劫持到了恶意钓鱼站点,然后继而会被钓鱼输入各种账号密码信息,泄漏隐私。 dns劫持 这类劫持,要不就是网络运营商搞的鬼,一般小的网络运营商与黑产勾结会劫持 DNS,要不就是电脑中毒,被恶意篡改了路由器的 DNS 配置,基本上做为开发者或站长却是很难察觉的,除非有用户反馈,现在升级版的 DNS 劫持还可以对特定用户、特定区域等使用了用户画像进行筛选用户劫持的办法,另外这类广告显示更加随机更小,一般站长除非用户投诉否则很难觉察到,就算觉察到了取证举报更难。无论如何,如果接到有 DNS 劫持的反馈,一定要做好以下几件事: 取证很重要,时间、地点、IP、拨号账户、截屏、URL 地址等一定要有。 可以跟劫持区域的电信运营商进行投诉反馈。 如果投诉反馈无效,直接去工信部投诉,一般来说会加白你的域名。 HTTP 劫持 HTTP 劫持您可以这么理解,「你打了一辆车想去商场吃饭,结果司机跟你一路给你递小作坊的广告」,HTTP 劫持主要是当用户访问某个站点的时候会经过运营商网络,而不法运营商和黑产勾结能够截获 HTTP 请求返回内容,并且能够篡改内容,然后再返回给用户,从而实现劫持页面,轻则插入小广告,重则直接篡改成钓鱼网站页面骗用户隐私。能够实施流量劫持的根本原因,是 HTTP 协议没有办法对通信对方的身份进行校验以及对数据完整性进行校验。如果能解决这个问题,则流量劫持将无法轻易发生。所以防止 HTTP 劫持的方法只有将内容加密,让劫持者无法破解篡改,这样就可以防止 HTTP 劫持了。 HTTPS 协议就是一种基于 SSL 协议的安全加密网络应用层协议,可以很好的防止 HTTP 劫持。这里有篇 文章 讲的不错。HTTPS 在这就不深讲了,后面有机会我会单独好好讲讲 HTTPS。如果不想站点被 HTTP 劫持,赶紧将你的站点全站改造成 HTTPS 吧。 服务器漏洞 服务器除了以上提到的那些大名鼎鼎的漏洞和臭名昭著的攻击以外,其实还有很多其他的漏洞,往往也很容易被忽视,在这个小节也稍微介绍几种。 越权操作漏洞 如果你的系统是有登录控制的,那就要格外小心了,因为很有可能你的系统越权操作漏洞,越权操作漏洞可以简单的总结为 「A 用户能看到或者操作 B 用户的隐私内容」,如果你的系统中还有权限控制就更加需要小心了。所以每一个请求都需要做 userid 的判断 以下是一段有漏洞的后端示意代码: // ctx 为请求的 context 上下文let msgId = ctx.params.msgId;mysql.query('SELECT FROM msg_table WHERE msg_id = ?',[msgId]); 以上代码是任何人都可以查询到任何用户的消息,只要有 msg_id 就可以,这就是比较典型的越权漏洞,需要如下这么改进一下: // ctx 为请求的 context 上下文let msgId = ctx.params.msgId;let userId = ctx.session.userId; // 从会话中取出当前登陆的 userIdmysql.query('SELECT FROM msg_table WHERE msg_id = ? AND user_id = ?',[msgId, userId]); 嗯,大概就是这个意思,如果有更严格的权限控制,那在每个请求中凡是涉及到数据库的操作都需要先进行严格的验证,并且在设计数据库表的时候需要考虑进 userId 的账号关联以及权限关联。 目录遍历漏洞 目录遍历漏洞指通过在 URL 或参数中构造 …/,./ 和类似的跨父目录字符串的 ASCII 编码、unicode 编码等,完成目录跳转,读取操作系统各个目录下的敏感文件,也可以称作「任意文件读取漏洞」。 目录遍历漏洞原理:程序没有充分过滤用户输入的 …/ 之类的目录跳转符,导致用户可以通过提交目录跳转来遍历服务器上的任意文件。使用多个… 符号,不断向上跳转,最终停留在根 /,通过绝对路径去读取任意文件。 目录遍历漏洞几个示例和测试,一般构造 URL 然后使用浏览器直接访问,或者使用 Web 漏洞扫描工具检测,当然也可以自写程序测试。 http://somehost.com/../../../../../../../../../etc/passwdhttp://somehost.com/some/path?file=../../Windows/system.ini 借助 %00 空字符截断是一个比较经典的攻击手法http://somehost.com/some/path?file=../../Windows/system.ini%00.js 使用了 IIS 的脚本目录来移动目录并执行指令http://somehost.com/scripts/..%5c../Windows/System32/cmd.exe?/c+dir+c:\ 防御 方法就是需要对 URL 或者参数进行 …/,./ 等字符的转义过滤。 物理路径泄漏 物理路径泄露属于低风险等级缺陷,它的危害一般被描述为「攻击者可以利用此漏洞得到信息,来对系统进一步地攻击」,通常都是系统报错 500 的错误信息直接返回到页面可见导致的漏洞。得到物理路径有些时候它能给攻击者带来一些有用的信息,比如说:可以大致了解系统的文件目录结构;可以看出系统所使用的第三方软件;也说不定会得到一个合法的用户名(因为很多人把自己的用户名作为网站的目录名)。 防止这种泄漏的方法就是做好后端程序的出错处理,定制特殊的 500 报错页面。 源码暴露漏洞 和物理路径泄露类似,就是攻击者可以通过请求直接获取到你站点的后端源代码,然后就可以对系统进一步研究攻击。那么导致源代码暴露的原因是什么呢?基本上就是发生在服务器配置上了,服务器可以设置哪些路径的文件才可以被直接访问的,这里给一个 koa 服务起的例子,正常的 koa 服务器可以通过 koa-static 中间件去指定静态资源的目录,好让静态资源可以通过路径的路由访问。比如你的系统源代码目录是这样的: |- project|- src|- static|- ...|- server.js 你想要将 static 的文件夹配成静态资源目录,你应该会在 server.js 做如下配置: const Koa = require('koa');const serve = require('koa-static');const app = new Koa();app.use(serve(__dirname + '/project/static')); 但是如果配错了静态资源的目录,可能就出大事了,比如: // ...app.use(serve(__dirname + '/project')); 这样所有的源代码都可以通过路由访问到了,所有的服务器都提供了静态资源机制,所以在通过服务器配置静态资源目录和路径的时候,一定要注意检验,不然很可能产生漏洞。 最后,希望 Web 开发者们能够管理好自己的代码隐私,注意代码安全问题,比如不要将产品的含有敏感信息的代码放到第三方外部站点或者暴露给外部用户,尤其是前端代码,私钥类似的保密性的东西不要直接输出在代码里或者页面中。也许还有很多值得注意的点,但是归根结底还是绷住安全那根弦,对待每一行代码都要多多推敲。 请关注我的订阅号 本篇文章为转载内容。原文链接:https://blog.csdn.net/MrCoderStack/article/details/88547919。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-03 14:51:12
493
转载
转载文章
...ser实例。在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
转载
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
lastlog
- 显示所有用户的最后登录时间及相关信息。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"