前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[Hadoop Distributed F...]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Java
...: list) { System.out.println(lang); } // 删除元素 list.remove("C++"); 3. Date和Calendar类处理日期时间 处理日期和时间时,我们会用到Date和Calendar类: java // 创建Date对象表示当前时间 Date now = new Date(); // 使用Calendar类获取特定日期信息 Calendar cal = Calendar.getInstance(); cal.setTime(now); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); System.out.printf("Current date is: %d-%d-%d", year, month + 1, day); 4. File类实现文件操作 File类提供了与文件系统交互的能力: java // 创建File对象 File file = new File("test.txt"); // 判断文件是否存在 boolean exists = file.exists(); // 创建新文件 file.createNewFile(); // 删除文件 file.delete(); 以上仅是Java众多常用类和方法的冰山一角,每个方法背后都蕴含着丰富的设计理念和技术细节。在实际敲代码的时候,咱们得根据实际情况灵活耍弄这些工具,不断动脑筋、动手尝试、一步步改进,才能真正把这些工具的精要吃透。同时,千万要记住,随着科技的日新月异,Java库可是一直在不断丰富和进化,时常有各种新鲜出炉、实用性爆棚的类和方法加入进来。这就是Java语言让人着迷的地方——它始终紧跟时代的步伐,始终保持年轻活力,为开发者们提供最高效、最省心省力的解决办法。
2023-01-06 08:37:30
348
桃李春风一杯酒
转载文章
.../获取所有图片的链接System.out.println(elements1);} }} 在分类页中有一个隐藏的问题图片: 正常的图片链接都是以“/”开头,以“.htm”结尾,而每个分类下的第三张图片的链接都是“http://pic.netbian.com/”,如果不过滤的话会报如下错误: 所以这里必须要判断一下: Elements elements = document.select("main .list li a");for (Element element : elements) {String href = element.attr("href");//判断是否是以“/”开头if (href.startsWith("/")) {String picUrl = "http://www.netbian.com" + href;Document document1 = Jsoup.connect(picUrl).get();Elements elements1 = document1.select(".endpage .pic p a img");System.out.println(elements1);} } 到这里,页面就已经分析好了,问题基本上已经解决了,接下来我们需要将图片存到我们的系统里,这里我将图片保存到我的电脑桌面上,并按照分类来存储图片。 首先是要获取桌面路径,在utils包下创建Download类,添加getDesktop方法,代码如下: public static File getDesktop(){FileSystemView fsv = FileSystemView.getFileSystemView();File path=fsv.getHomeDirectory(); return path;} 接着我们再该类中添加下载图片的方法: //urlPath为网络图片的路径,savePath为要保存的本地路径(这里指定为桌面下的images文件夹)public static void download(String urlPath,String savePath) throws Exception {// 构造URLURL url = new URL(urlPath);// 打开连接URLConnection con = url.openConnection();//设置请求超时为5scon.setConnectTimeout(51000);// 输入流InputStream is = con.getInputStream();// 1K的数据缓冲byte[] bs = new byte[1024];// 读取到的数据长度int len;// 输出的文件流File sf=new File(savePath);int randomNo=(int)(Math.random()1000000);String filename=urlPath.substring(urlPath.lastIndexOf("/")+1,urlPath.length());//获取服务器上图片的名称filename=new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())+randomNo+filename;//时间+随机数防止重复OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);// 开始读取while ((len = is.read(bs)) != -1) {os.write(bs, 0, len);}// 完毕,关闭所有链接os.close();is.close();} 写好后,我们再完善一下JsouPic中的getPic方法。 public static void getPic(String kind) throws Exception {//get请求方式进行请求Document root_doc = Jsoup.connect("http://www.netbian.com/" + kind + "/").get();//获取分页标签,用于获取总页数Elements els = root_doc.select("main .page a");Integer page = Integer.parseInt(els.eq(els.size() - 2).text());for (int i = 1; i < page; i++) {Document document = null;//这里判断的是当前页号是否为1,如果为1就不拼页号,否则拼上对应的页号if (i == 1) {document = Jsoup.connect("http://www.netbian.com/" + kind + "/index.htm").get();} else {document = Jsoup.connect("http://www.netbian.com/" + kind + "/index_" + i + ".htm").get();}File desktop = Download.getDesktop();Download.checkPath(desktop.getPath() + "\\images\\" + kind);//获取每个分页链接里面a标签的链接,进入链接页面获取当前图拼的大尺寸图片Elements elements = document.select("main .list li a");for (Element element : elements) {String href = element.attr("href");if (href.startsWith("/")) {String picUrl = "http://www.netbian.com" + href;Document document1 = Jsoup.connect(picUrl).get();Elements elements1 = document1.select(".endpage .pic p a img");Download.download(elements1.attr("src"), desktop.getPath() + "\\images\\" + kind);} }} } 在Download类中,我添加了checkPath方法,用于判断目录是否存在,不存在就创建一个。 public static void checkPath(String savePath) throws Exception {File file = new File(savePath);if (!file.exists()){file.mkdirs();} } 最后在mainapp包内创建PullPic类,并添加主方法。 package com.asahi.mainapp;import com.asahi.common.Kind;import com.asahi.common.PrintLog;import com.asahi.utils.JsoupPic;import java.util.Scanner;public class PullPic {public static void main(String[] args) throws Exception {new PullPic().downloadPic();}public void downloadPic() throws Exception {System.out.println("启动程序>>\n请输入所爬取的分类:");Scanner scanner = new Scanner(System.in);String kind = scanner.next();while(!Kind.contains(kind)){System.out.println("分类不存在,请重新输入:");kind = scanner.next();}System.out.println("分类输入正确!");System.out.println("开始下载>>");JsoupPic.getPic(kind);} } 三、成果展示 最终的运行结果如下: 最终的代码已上传到我的github中,点击“我的github”进行查看。 在学习Java爬虫的过程中,我收获了很多,一开始做的时候确实遇到了很多困难,这次写的获取图片也是最基础的,还可以继续深入。本来我想写一个通过多线程来获取图片来着,也尝试着去写了一下,越写越跑偏,暂时先放着不处理吧,等以后有时间再来弄,我想问题应该不大,只是考虑的东西有很多。希望大家多多指点不足,有哪些需要改进的地方,我也好多学习学习๑乛◡乛๑。 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_39693281/article/details/108463868。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-06-12 10:26:04
130
转载
ZooKeeper
...broker节点;在Hadoop生态系统中,它为YARN资源管理和HBase元数据存储提供了强大的支持。 近日,Apache ZooKeeper社区宣布即将发布3.8.0版本,其中包含了对事件处理性能的优化以及一些新特性支持。这一版本更新将进一步强化ZooKeeper在大规模分布式环境下的响应能力和稳定性。同时,社区也在积极探索与容器化、Service Mesh等新兴技术的深度集成方案,以适应云时代的快速发展。 对于希望更深入研究ZooKeeper的读者,可以关注官方发布的开发文档和技术博客,了解最新版本特性及最佳实践。此外,《ZooKeeper: Distributed Process Coordination》一书提供了对ZooKeeper内部原理和应用场景的详尽解读,是进一步学习的理想资料。通过紧跟前沿技术和深化理论知识,开发者能够更好地利用ZooKeeper解决实际工程中的分布式协调问题,提升系统的整体效能和可靠性。
2023-02-09 12:20:32
116
繁华落尽
Mahout
...home/user/hadoop/logs/mapred/jobhistory/done"); FileSystem fs = FileSystem.get(conf); Path cacheDir = new Path("/cache"); fs.mkdirs(cacheDir); conf.set("mapred.cache.files", cacheDir.toString()); 四、结论 总的来说,通过合理地使用流式处理和降低向量化模型的精度,我们可以有效地优化内存使用。同时,通过使用数据缓存,我们可以有效地优化磁盘I/O。这些都是我们在处理大数据时需要注意的问题。当然啦,这只是个入门级别的小建议,具体的优化方案咱们还得瞅瞅实际情况再灵活制定哈。希望这篇文章能对你有所帮助,让你更好地利用Mahout处理大数据!
2023-04-03 17:43:18
87
雪域高原-t
Kylin
...Kylin是一个基于Hadoop的数据仓库工具,其主要目标是提供一个快速查询分析海量数据的方式。本文将分享我在使用Kylin进行报表设计过程中的一些经验和技巧。 二、Kylin的优势 首先,让我们来了解一下Kylin的优点。Kylin在对付大数据的时候,可真是展现出了超凡的实力,为啥呢?因为它用了一种叫“多维立方体”的独门数据结构。这就像是给数据装上了一辆超级跑车,让数据访问速度嗖嗖地往上窜,效果显著到不行!另外,Kylin还特别贴心地提供了超级灵活的查询语句支持,让你能够按照自己的小心愿,随心所欲地定制SQL查询语句,这样一来,就能轻松捞到更加精确无比的结果啦! 三、如何开始 开始使用Kylin的第一步就是创建一个项目。在Kylin的网页界面里头,瞅准那个醒目的“新建项目”按钮,给它轻轻一点,接着就可以麻溜地输入你项目的响亮大名和其他一些必要的细节信息啦。接着,你需要配置你的Hadoop集群信息,包括HDFS地址、JobTracker地址等。最后,点击"提交"按钮,Kylin就会开始创建你的项目。 java // 创建一个新的Kylin项目 ClientService client = ClientService.getInstance(); ProjectMeta meta = new ProjectMeta(); meta.setName("my_project"); meta.setHiveUrl("hdfs://localhost:9000"); meta.setHiveUser("hive"); meta.setHivePasswd("hive"); client.createProject(meta); 四、数据模型设计 在Kylin中,我们通常需要对我们的数据进行建模,以便于后续的查询操作。Kylin提供了两种数据模型:维度模型和事实模型。维度模型,你把它想象成一个大大的资料夹,里面装着实体的各种详细信息,像是什么时间发生的、在哪个地点、属于哪种产品类型等等;而事实模型呢,就更像是个记账本,专门用来记录实体的各种行为表现,像卖了多少货、交易额有多少这些具体的数字信息。 java // 创建一个新的维度模型 DimensionModelDesc modelDesc = new DimensionModelDesc(); modelDesc.setName("my_dim_model"); modelDesc.setColumns(Arrays.asList(new ColumnDesc("dim_date", "date"), new ColumnDesc("dim_location", "string"))); client.createDimModel(modelDesc); // 创建一个新的事实模型 FactModelDesc factModelDesc = new FactModelDesc(); factModelDesc.setName("my_fact_model"); factModelDesc.setColumns(Arrays.asList(new ColumnDesc("fact_sales", "bigint"))); factModelDesc.setDimensions(Arrays.asList("my_dim_model")); client.createFactModel(factModelDesc); 五、报表设计与查询 接下来,我们可以开始设计我们的报表了。在Kylin这个工具里头,我们能够像平常一样用标准的SQL查询语句去查数据,然后把查出来的结果,随心所欲地转换成各种格式保存,比如说CSV啦、Excel表格什么的,超级方便。 java // 查询指定日期的销售数据 String sql = "SELECT dim_date, SUM(fact_sales) FROM my_fact_model GROUP BY dim_date"; CubeInstance cube = CubeManager.getInstance().getCube("my_cube"); List rows = cube.cubeQuery(sql); for (Row row : rows) { System.out.println(row.getString(0) + ": " + row.getLong(1)); } 六、总结 总的来说,Kylin是一个非常强大的数据分析工具,它可以帮助我们轻松地处理大量的数据,并且提供了丰富的查询功能,使得我们能够更方便地获取所需的信息。如果你也在寻找一种高效的数据分析解决方案,那么我强烈推荐你试试Kylin。
2023-05-03 20:55:52
111
冬日暖阳-t
Flink
...现了与多种存储系统如Hadoop HDFS和阿里云OSS的无缝对接,显著提升了整体业务流程的响应速度和吞吐量。这一实战经验为行业内外的大数据从业者提供了宝贵参考。 此外,针对异步编程模型的深入解读与探讨也不容忽视。例如,知名论文《Asynchronous Programming Models for Big Data Processing》中,作者从理论层面剖析了异步I/O在分布式系统及大数据处理中的核心价值,并结合具体案例阐述了其在降低延迟、提高资源利用率等方面的优越表现。这些前沿研究成果对于指导实际工程实践以及未来技术创新具有重要意义。
2024-01-09 14:13:25
492
幽谷听泉-t
Hive
...ve其实就像是个建在Hadoop上的“数据仓库”,它能帮我们把有条理的数据存到HDFS里,然后用类似SQL的语句去查询和处理这些数据,特别方便!Hive默认支持一些常见的压缩格式,比如Snappy、LZO等。哎呀,你要是想用GZIP或者BZIP2来存表,那可得小心点啊!没准Hive会直接给你整出个错误,连数据都不让你加载。这到底是咋回事儿呢?其实吧,这是因为这两种压缩方式的性格和Hive的理念不太合拍。简单来说,它们的玩法不一样,所以Hive就觉得有点不爽,干脆就不让你这么干了。 那么问题来了:既然Hive不支持它们,为什么我们还要去折腾这些“非主流”压缩格式呢?我的回答是:因为它们可能真的有用!比如,GZIP非常适合用于压缩单个文件,而BZIP2则在某些场景下能提供更高的压缩比。所以说嘛,官方案子虽然说了不让搞,但我们不妨大胆试试,看看这些玩意儿到底能整出啥名堂! --- 二、理论基础 GZIP vs BZIP2 vs Hive的“规则” 在深入讨论具体操作之前,我们得先搞清楚这三个东西之间的差异。嘿,先说个大家可能都知道的小秘密——GZIP可是个超火的压缩“神器”呢!它最大的特点就是又快又好用,压缩文件的速度嗖一下就搞定了,效果也还行,妥妥的性价比之王!而BZIP2则是另一种高级压缩算法,虽然压缩比更高,但速度相对较慢。相比之下,Hive好像更喜欢找那种“全能型选手”,就像Snappy这种,又快又能省资源,简直两全其美! 现在问题来了:既然Hive有自己的偏好,那我们为什么要挑战它的权威呢?答案很简单:现实世界中的需求往往比理想模型复杂得多。比如说啊,有时候我们有一堆小文件,东一个西一个的,看着就头疼,想把它们整整齐齐地打包成一个大文件存起来,这时候用GZIP就很方便啦!但要是你手头的数据量超级大,比如几百万张高清图片那种,而且你还特别在意压缩效果,希望能榨干每一丢丢空间,那BZIP2就更适合你了,它在这方面可是个狠角色! 当然,这一切的前提是我们能够绕过Hive对这些格式的限制。接下来,我们就来看看具体的解决方案。 --- 三、实践篇 如何让Hive接受GZIP和BZIP2? 3.1 GZIP的逆袭之路 让我们从GZIP开始说起。想象一下,你有个文件夹,专门用来存各种日志文件,里面的文件可多啦!不过呢,这些文件都特别小巧,大概就几百KB的样子,像是些小纸条,记录着各种小事。哎呀,要是直接把一堆小文件一股脑儿塞进HDFS里,那可就麻烦了!这么多小文件堆在一起,系统就会变得特别卡,整体性能直线下降,简直像路上突然挤满了慢吞吞的小汽车,堵得不行!要解决这个问题嘛,咱们可以先把文件用GZIP压缩一下,弄个小“压缩包”,然后再把它丢进Hive里头去。 下面是一段示例代码,展示了如何创建一个支持GZIP格式的外部表: sql -- 创建数据库 CREATE DATABASE IF NOT EXISTS log_db; -- 切换到数据库 USE log_db; -- 创建外部表并指定GZIP格式 CREATE EXTERNAL TABLE IF NOT EXISTS logs ( id STRING, timestamp STRING, message STRING ) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' STORED AS TEXTFILE -- 注意这里使用TEXTFILE而不是默认的SEQUENCEFILE LOCATION '/path/to/gzipped/files'; 看到这里,你可能会问:“为什么这里要用TEXTFILE而不是SEQUENCEFILE?”这是因为Hive默认不支持直接读取GZIP格式的数据,所以我们需要手动调整存储格式。此外,还需要确保你的Hadoop集群已经启用了GZIP解压功能。 3.2 BZIP2的高阶玩法 接下来轮到BZIP2登场了。相比于GZIP,BZIP2的压缩比更高,但它也有一个明显的缺点:解压速度较慢。因此,BZIP2更适合用于那些访问频率较低的大规模静态数据集。 下面这段代码展示了如何创建一个支持BZIP2格式的分区表: sql -- 创建数据库 CREATE DATABASE IF NOT EXISTS archive_db; -- 切换到数据库 USE archive_db; -- 创建分区表并指定BZIP2格式 CREATE TABLE IF NOT EXISTS archives ( file_name STRING, content STRING ) PARTITIONED BY (year INT, month INT) STORED AS RCFILE -- RCFILE支持BZIP2压缩 TBLPROPERTIES ("orc.compress"="BZIP2"); 需要注意的是,在这种情况下,你需要确保Hive的配置文件中启用了BZIP2支持,并且相关的JAR包已经正确安装。 --- 四、实战经验分享 踩过的坑与学到的东西 在这个过程中,我遇到了不少挫折。比如说吧,有次我正打算把一个GZIP文件塞进Hive里,结果系统直接给我整了个报错,说啥解码器找不着。折腾了半天才发现,哎呀,原来是服务器上那个GZIP工具的老版本太不给劲了,跟最新的Hadoop配不上,闹起了脾气!于是,我赶紧联系运维团队升级了相关依赖,这才顺利解决问题。 还有一个教训是关于文件命名规范的。一开始啊,我老是忘了在压缩完的文件后面加“.gz”或者“.bz2”这种后缀名,搞得 Hive 一脸懵逼,根本分不清文件是啥类型的,直接就报错不认账了。后来我才明白,那些后缀名可不只是个摆设啊,它们其实是给文件贴标签的,告诉你这个文件是啥玩意儿,是图片、音乐,还是什么乱七八糟的东西。 --- 五、总结与展望 总的来说,虽然Hive对GZIP和BZIP2的支持有限,但这并不意味着我们不能利用它们的优势。相反,只要掌握了正确的技巧,我们完全可以在这两者之间找到平衡点,满足不同的业务需求。 最后,我想说的是,作为一名数据工程师,我们不应该被工具的限制束缚住手脚。相反,我们应该敢于尝试新事物,勇于突破常规。毕竟,正是这种探索精神,推动着整个行业不断向前发展! 好了,今天的分享就到这里啦。如果你也有类似的经历或者想法,欢迎随时跟我交流哦~再见啦!
2025-04-19 16:20:43
45
翡翠梦境
Hadoop
Hadoop支持文件的跨硬件复制 1. 初识Hadoop 为什么我们需要它? 大家好!今天我们要聊聊一个超级酷的东西——Hadoop。作为一个程序员或者数据工程师,你可能已经听说过这个名字。Hadoop是一种开源的大数据处理框架,它的核心功能是存储和处理海量的数据。不过,我今天想带大家深入探讨的是Hadoop的一个非常实用的功能:跨硬件复制文件。 为什么这个功能这么重要呢?想象一下,如果你正在运行一个大型的分布式系统,突然某个节点挂了怎么办?数据丢了?那可太惨了!Hadoop通过分布式文件系统(HDFS)来解决这个问题。HDFS 可不只是简单地把大文件切成小块儿,它还特聪明,会把这些小块儿分散存到不同的机器上。这就跟把鸡蛋放在好几个篮子里一个道理,哪怕有一台机器突然“罢工”了(也就是挂掉了),你的数据还是稳稳的,一点都不会丢。 那么,Hadoop是如何做到这一点的呢?咱们先来看看它是怎么工作的。 --- 2. HDFS的工作原理 数据块与副本 HDFS是一个分布式的文件系统,它的设计理念就是让数据更加可靠。简单讲啊,HDFS会把一个大文件切成好多小块儿(每块默认有128MB这么大),接着把这些小块分开放到集群里的不同电脑上存着。更关键的是,HDFS会为每个数据块多弄几个备份,一般是三个副本。这就相当于给你的数据买了“多重保险”,哪怕有一台机器突然“罢工”或者出问题了,你的数据还是妥妥地躺在别的机器上,一点都不会丢。 举个例子,假设你有一个1GB的文件,HDFS会把这个文件分成8个128MB的小块,并且每个小块会被复制成3份,分别存储在不同的服务器上。这就意味着啊,就算有一台服务器“挂了”或者出问题了,另外两台服务器还能顶上,数据照样能拿得到,完全不受影响。 说到这里,你可能会问:“为什么要复制这么多份?会不会浪费空间?”确实,多副本策略会占用更多的磁盘空间,但它的优点远远超过这一点。先说白了就是,它能让数据更好用、更靠谱啊!再说了,在那种超大的服务器集群里头,这样的备份机制还能帮着分散压力,不让某一个地方出问题就整个崩掉。 --- 3. 实战演示 如何使用Hadoop进行跨硬件复制? 接下来,让我们动手试试看!我会通过一些实际的例子来展示Hadoop是如何完成文件跨硬件复制的。 3.1 安装与配置Hadoop 首先,你需要确保自己的环境已经安装好了Hadoop。如果你还没有安装,可以参考官方文档一步步来配置。对新手来说,建议先试试伪分布式模式,相当于在一台电脑上“假装”有一个完整的集群,方便你熟悉环境又不用折腾多台机器。 3.2 创建一个简单的文本文件 我们先创建一个简单的文本文件,用来测试Hadoop的功能。你可以使用以下命令: bash echo "Hello, Hadoop!" > test.txt 然后,我们将这个文件上传到HDFS中: bash hadoop fs -put test.txt /user/hadoop/ 这里的/user/hadoop/是HDFS上的一个目录路径。 3.3 查看文件的副本分布 上传完成后,我们可以检查一下这个文件的副本分布情况。使用以下命令: bash hadoop fsck /user/hadoop/test.txt -files -blocks -locations 这段命令会输出类似如下的结果: /user/hadoop/test.txt 128 bytes, 1 block(s): OK 0. BP-123456789-192.168.1.1:50010 file:/path/to/local/file 1. BP-123456789-192.168.1.2:50010 file:/path/to/local/file 2. BP-123456789-192.168.1.3:50010 file:/path/to/local/file 从这里可以看到,我们的文件已经被复制到了三台不同的服务器上。 --- 4. 深度解读 Hadoop的副本策略 在前面的步骤中,我们已经看到了Hadoop是如何将文件复制到不同节点上的。但是,你知道吗?Hadoop的副本策略其实是非常灵活的。它可以根据网络拓扑结构来决定副本的位置。 例如,默认情况下,第一个副本会放在与客户端最近的节点上,第二个副本会放在另一个机架上,而第三个副本则会放在同一个机架的不同节点上。这样的策略可以最大限度地减少网络延迟,提高读取效率。 当然,如果你对默认的副本策略不满意,也可以自己定制。比如,如果你想让所有副本都放在同一个机架内,可以通过修改dfs.replication.policy参数来实现。 --- 5. 总结与展望 通过今天的讨论,我们了解了Hadoop是如何通过HDFS实现文件的跨硬件复制的。虽然这个功能看似简单,但它背后蕴含着复杂的设计理念和技术细节。正是这些设计,才使得Hadoop成为了一个强大的大数据处理工具。 最后,我想说的是,学习新技术的过程就像探险一样,充满了未知和挑战。嘿,谁还没遇到过点麻烦事儿呢?有时候一头雾水,感觉前路茫茫,但这不正是探索的开始嘛!别急着放弃,熬过去你会发现,那些让人头疼的问题其实藏着不少小惊喜,等你拨开云雾时,成就感绝对让你觉得值了!希望这篇文章能给你带来一些启发,也希望你能亲自尝试一下Hadoop的实际操作,感受一下它的魅力! 好了,今天的分享就到这里啦!如果你有任何疑问或者想法,欢迎随时留言交流。让我们一起探索更多有趣的技术吧!
2025-03-26 16:15:40
97
冬日暖阳
Hadoop
HDFS读取速度慢?别急,我们一起来找原因! 最近我在使用Hadoop的过程中,发现了一个让我非常头疼的问题——HDFS的读取速度慢得让人抓狂!作为一个对大数据技术充满热情的技术宅男(或者宅女),这种问题简直就像一道数学题里的“未知数”一样困扰着我。今天,我就想跟大家聊聊这个话题,希望能找到一些解决办法。 一、背景介绍 HDFS为什么重要? 首先,让我们简单回顾一下HDFS是什么。HDFS(Hadoop分布式文件系统)就像是Hadoop这个大家族里的“顶梁柱”之一,它专门用来管理海量的数据,就像一个超级大的仓库,能把成千上万的数据文件整整齐齐地存放在不同的电脑上,还能保证它们既安全又容易取用。简单来说,就是把一个大文件分成很多小块,然后把这些小块分散存储在不同的服务器上。这么做的好处嘛,简直太明显了!就算哪台机器突然“罢工”了,数据也能稳稳地保住,完全不会丢。而且呢,还能同时对这些数据进行处理,效率杠杠的! 但是,任何技术都有它的局限性。HDFS虽然功能强大,但在实际应用中也可能会遇到各种问题,比如读取速度慢。这可能是由于网络延迟、磁盘I/O瓶颈或者其他因素造成的。那么,具体有哪些原因会导致HDFS读取速度变慢呢?接下来,我们就来一一分析。 二、可能的原因及初步排查 1. 网络延迟过高 想象一下,你正在家里看电影,突然发现画面卡顿了,这是因为你的网络连接出了问题。同样地,在HDFS中,如果网络延迟过高,也会导致读取速度变慢。比如说,假如你的数据节点散落在天南海北的各种数据中心里,那数据跑来跑去就得花更多时间,就像你在城市两端都有家一样,来回折腾肯定比在同一个小区里串门费劲得多。 示例代码: java Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); Path filePath = new Path("/user/hadoop/input/file.txt"); FSDataInputStream in = null; try { in = fs.open(filePath); byte[] buffer = new byte[1024]; int bytesRead = in.read(buffer); while (bytesRead != -1) { bytesRead = in.read(buffer); } } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } 这段代码展示了如何从HDFS中读取文件。如果你发现每次执行这段代码时都需要花费很长时间,那么很可能是网络延迟的问题。 2. 数据本地性不足 还记得小时候玩过的接力赛吗?如果接力棒总是从一个人传到另一个人再传回来,效率肯定不高。这就跟生活中的事儿一样啊,在HDFS里头,要是数据没分配到离客户端最近的那个数据节点上,那不是干等着嘛,多浪费时间呀! 解决方案: 可以通过调整副本策略来改善数据本地性。比如说,默认设置下,HDFS会把文件的备份分散存到集群里的不同机器上。不过呢,如果你想让这个过程变得更高效或者更适合自己的需求,完全可以去调整那个叫dfs.replication的参数! xml dfs.replication 3 3. 磁盘I/O瓶颈 磁盘读写速度是影响HDFS性能的一个重要因素。要是你的服务器用的是那些老掉牙的机械硬盘,那读文件的速度肯定就慢得像乌龟爬了。 实验验证: 为了测试磁盘I/O的影响,可以尝试将一部分数据迁移到SSD上进行对比实验。好啦,想象一下,你手头有一堆日志文件要对付。先把它们丢到普通的老硬盘(HDD)里待着,然后又挪到固态硬盘(SSD)上,看看读取速度变了多少。是不是感觉像在玩拼图游戏,只不过这次是在折腾文件呢? 三、进阶优化技巧 经过前面的分析,我们可以得出结论:要提高HDFS的读取速度,不仅仅需要关注硬件层面的问题,还需要从软件配置上下功夫。以下是一些更高级别的优化建议: 1. 增加带宽 带宽就像是高速公路的车道数量,车道越多,车辆通行就越顺畅。对于HDFS来说,增加带宽意味着可以同时传输更多的数据块。 实际操作: 联系你的网络管理员,询问是否有可能升级现有的网络基础设施,比如更换更快的交换机或者部署新的光纤线路。 2. 调整副本策略 默认情况下,HDFS会将每个文件的三个副本均匀分布在整个集群中。然而,在某些特殊场景下,这种做法并不一定是最优解。比如说,你家APP平时就爱扎堆在那几个服务器节点上干活儿,那就可以把副本都放一块儿,这样它们串门聊天、传文件啥的就方便多了,也不用跑太远浪费时间啦! 配置修改: xml dfs.block.local-path-access.enabled true 3. 使用缓存机制 缓存就像冰箱里的剩饭,拿出来就能直接吃,不用重新加热。HDFS也有类似的机制,叫做“DataNode Cache”。打开这个功能之后啊,那些经常用到的数据就会被暂时存到内存里,这样下次再用的时候就嗖的一下快多了! 启用步骤: bash hadoop dfsadmin -setSpaceQuota 100g /cachedir hadoop dfs -cache /inputfile /cachedir 四、总结与展望 通过今天的讨论,我相信大家都对HDFS读取速度慢的原因有了更深的理解。其实,无论是网络延迟、数据本地性还是磁盘I/O瓶颈,都不是不可克服的障碍。其实吧,只要咱们肯花点心思去琢磨、去试试,肯定能找出个适合自己情况的办法。 最后,我想说的是,作为一名技术人员,我们应该始终保持好奇心和探索精神。不要害怕失败,也不要急于求成,因为每一次挫折都是一次成长的机会。希望这篇文章能给大家带来启发,让我们一起努力,让Hadoop变得更加高效可靠吧! --- 以上就是我对“HDFS读取速度慢”的全部看法和建议。如果你还有其他想法或者遇到类似的问题,请随时留言交流。咱们共同进步,一起探索大数据世界的奥秘!
2025-05-04 16:24:39
103
月影清风
Kylin
...布式分析工具,它能在Hadoop之上让你用SQL来查询数据,还能进行复杂的多维分析(OLAP),处理起超大规模的数据来毫不含糊。这个项目最早是eBay的大佬们搞出来的,后来他们把它交给了Apache基金会,让它成为大家共同的宝贝。在用Kylin的时候,我真是遇到了一堆麻烦事儿,从设置到安装,再到调整性能,每一步都像是在闯关。嘿,今天我打算分享点实用的东西。基于我个人的经验,咱们来聊聊在配置和部署Kylin时会遇到的一些常见坑,还有我是怎么解决这些麻烦的。准备好了吗?让我们一起避开这些小陷阱吧! 2. Kylin环境搭建 首先,我们来谈谈环境搭建。搭建Kylin环境需要一些基本的软件支持,如Java、Hadoop、HBase等。我刚开始的时候就因为没有正确安装这些软件而走了不少弯路。比如我以前试过用Java 8跑Kylin,结果发现好多功能都用不了。后来才知道是因为Java版本太低了,怪自己当初没注意。所以在启动之前,记得检查一下你的电脑上是不是已经装了Java 11或者更新的版本,最好是长期支持版(LTS),这样Kylin才能乖乖地跑起来。 java 检查Java版本 java -version 接下来是Hadoop和HBase的安装。如果你用的是Cloudera CDH或者Hortonworks HDP,那安装起来就会轻松不少。但如果你是从源码编译安装,那么可能会遇到更多问题。比如说,我之前碰到过Hadoop配置文件里的一些参数不匹配,结果Kylin就启动不了。要搞定这个问题,关键就是得仔仔细细地检查一下配置文件,确保所有的参数都跟官方文档上说的一模一样。 xml 在hadoop-env.sh中设置JAVA_HOME export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64 3. Kylin配置详解 在完成环境搭建后,我们需要对Kylin进行配置。Kylin的配置主要集中在kylin.properties文件中。这个文件包含了Kylin运行所需的几乎所有参数。我头一回设置的时候,因为对那些参数不太熟悉,结果Kylin愣是没启动起来。后来经过多次尝试和查阅官方文档,我才找到了正确的配置方法。 一个常见的问题是,如何设置Kylin的存储位置。默认情况下,Kylin会将元数据存储在HBase中。不过,如果你想把元数据存在本地的文件系统里,只需要调整一下kylin.metadata.storage这个参数就行啦。这可以显著提高开发阶段的效率,但在生产环境中并不推荐这样做。 properties 设置Kylin元数据存储为本地文件系统 kylin.metadata.storage=fs:/path/to/local/directory 另一个重要的配置是Kylin的Cube构建策略。Cube是Kylin的核心概念之一,它用于加速查询响应时间。不同的Cube构建策略会影响查询性能和存储空间的占用。我曾经因为选择了错误的构建策略而导致Cube构建速度极慢。后来,通过调整kylin.cube.algorithm参数,我成功地优化了Cube构建过程。 properties 设置Cube构建策略为INMEM kylin.cube.algorithm=INMEM 4. Kylin部署与监控 最后,我们来谈谈Kylin的部署与监控。Kylin提供了多种部署方式,包括单节点部署、集群部署等。对于初学者来说,单节点部署可能更易于理解和操作。但是,随着数据量的增长,单节点部署很快就会达到瓶颈。这时,就需要考虑集群部署方案。 在部署过程中,我遇到的一个主要问题是服务之间的依赖关系。Kylin依赖于Hadoop和HBase,如果这些服务没有正确配置,Kylin将无法启动。要搞定这个问题,就得细细排查每个服务的状况,确保它们都乖乖地在运转着。 bash 检查Hadoop服务状态 sudo systemctl status hadoop-hdfs-namenode 部署完成后,监控Kylin的运行状态变得非常重要。Kylin提供了Web界面和日志文件两种方式来进行监控。你可以直接在网页上看到Kylin的各种数据指标,就像看仪表盘一样。至于Kylin的操作记录嘛,就都记在日志文件里头了。我经常使用日志文件来排查问题,因为它能提供更多的上下文信息。 bash 查看Kylin日志文件 tail -f /opt/kylin/logs/kylin.log 结语 通过这次分享,我希望能让大家对Kylin的配置与部署有一个更全面的理解。尽管在过程中会碰到各种难题,但只要咱们保持耐心,不断学习和探索,肯定能找到解决的办法。Kylin 的厉害之处就在于它超级灵活,还能随意扩展,这正是我们在大数据分析里头求之不得的呢。希望你们在使用Kylin的过程中也能感受到这份乐趣! --- 希望这篇技术文章对你有所帮助!如果你有任何疑问或需要进一步的帮助,请随时联系我。
2024-12-31 16:02:29
28
诗和远方
Mahout
...ahout是一个基于Hadoop的机器学习库,旨在利用分布式计算资源来加速大规模数据集上的算法执行。哎呀,这个家伙可真厉害!它能用上各种各样的机器学习魔法,比如说分门别类的技巧(就是咱们说的分类)、把相似的东西归到一块儿的本事(聚类)还有能给咱们推荐超棒东西的神奇技能(推荐系统)。而且,它最擅长的就是对付那些海量的数据,就像大鱼吃小鱼一样,毫不费力就能搞定!通过Mahout,我们可以构建复杂的模型来挖掘数据中的模式和关系,从而驱动业务决策。 3. Spark Streaming简介 Apache Spark Streaming是Spark生态系统的一部分,专为实时数据流处理设计。哎呀,这个玩意儿简直就是程序员们的超级神器!它能让咱这些码农兄弟们轻松搞定那些超快速、高效率的实时应用,你懂的,就是那种分秒必争、数据飞速流转的那种。想象一下,一秒钟能处理几千条数据,那感觉简直不要太爽啊!就像是在玩转数据的魔法世界,每一次点击都是对速度与精准的极致追求。这不就是我们程序员的梦想吗?在数据的海洋里自由翱翔,每一刻都在创造奇迹!Spark Streaming的精髓就像个魔术师,能把连续不断的水流(数据流)变换成小段的小溪(微批次)。这小溪再通过Spark这个强大的分布式计算平台,就像是在魔法森林里跑的水车,一边转一边把水(数据)处理得干干净净。这样一来,咱们就能在实时中捕捉到信息的脉动,做出快速反应,既高效又灵活! 4. Mahout与Spark Streaming的集成 为了将Mahout的机器学习能力与Spark Streaming的实时处理能力结合起来,我们需要创建一个流水线,使得Mahout可以在实时数据流上执行分析任务。这可以通过以下步骤实现: - 数据接入:首先,我们需要将实时数据流接入Spark Streaming。这可以通过定义一个DStream(Data Stream)对象来完成,该对象代表了数据流的抽象表示。 scala import org.apache.spark.streaming._ import org.apache.spark.streaming.dstream._ val sparkConf = new SparkConf().setAppName("RealtimeMahoutAnalysis").setMaster("local[2]") val sc = new SparkContext(sparkConf) valssc = new StreamingContext(sc, Seconds(1)) // 创建StreamingContext,时间间隔为1秒 val inputStream = TextFileStream("/path/to/your/data") // 假设数据来自文件系统 val dstream = inputStream foreachRDD { rdd => rdd.map { line => val fields = line.split(",") (fields(0), fields.slice(1, fields.length)) } } - Mahout模型训练:然后,我们可以使用Mahout中的算法对数据进行预处理和建模。例如,假设我们想要进行用户行为的聚类分析,可以使用Mahout的KMeans算法。 scala import org.apache.mahout.cf.taste.hadoop.recommender.KNNRecommender import org.apache.mahout.cf.taste.impl.model.file.FileDataModel import org.apache.mahout.cf.taste.impl.neighborhood.ThresholdUserNeighborhood import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity import org.apache.mahout.math.RandomAccessSparseVector import org.apache.hadoop.conf.Configuration val dataModel = new FileDataModel(new File("/path/to/your/data.csv")) val neighborhood = new ThresholdUserNeighborhood(0.5, dataModel, new Configuration()) val similarity = new PearsonCorrelationSimilarity(dataModel) val recommender = new GenericUserBasedRecommender(dataModel, neighborhood, similarity) val recommendations = dstream.map { (user, ratings) => val userVector = new RandomAccessSparseVector(ratings.size()) for ((itemId, rating) <- ratings) { userVector.setField(itemId.toInt, rating.toDouble) } val recommendation = recommender.recommend(user, userVector) (user, recommendation.map { (itemId, score) => (itemId, score) }) } - 结果输出:最后,我们可以将生成的推荐结果输出到合适的目标位置,如日志文件或数据库,以便后续分析和应用。 scala recommendations.foreachRDD { rdd => rdd.saveAsTextFile("/path/to/output") } 5. 总结与展望 通过将Mahout与Spark Streaming集成,我们能够构建一个强大的实时流数据分析平台,不仅能够实时处理大量数据,还能利用Mahout的高级机器学习功能进行深入分析。哎呀,这个融合啊,就像是给数据分析插上了翅膀,能即刻飞到你眼前,又准确得不得了!这样一来,咱们做决定的时候,心里那根弦就更紧了,因为有它在身后撑腰,决策那可是又稳又准,妥妥的!哎呀,随着科技车轮滚滚向前,咱们的Mahout和Spark Streaming这对好搭档,未来肯定会越来越默契,联手为我们做决策时,用上实时数据这个大宝贝,提供更牛逼哄哄的武器和方法!想象一下,就像你用一把锋利的剑,能更快更准地砍下胜利的果实,这俩家伙在数据战场上,就是那把超级厉害的宝剑,让你的决策快人一步,精准无比! --- 以上内容是基于实际的编程实践和理论知识的融合,旨在提供一个从概念到实现的全面指南。哎呀,当真要将这个系统或者项目实际铺展开来的时候,咱们得根据手头的实际情况,比如数据的个性、业务的流程和咱们的技术底子,来灵活地调整策略,让一切都能无缝对接,发挥出最大的效用。就像是做菜,得看食材的新鲜度,再搭配合适的调料,才能做出让人满意的美味佳肴一样。所以,别死板地照搬方案,得因地制宜,因材施教,这样才能确保我们的工作既高效又有效。
2024-09-06 16:26:39
59
月影清风
.net
... 在C中,文件流(FileStream)是System.IO命名空间下的一种类,它允许我们以流的形式对文件进行高效、灵活的读写操作。主要分为两种基本类型: - 读取流(Read Stream):如FileReadStream,用于从文件中读取数据。 - 写入流(Write Stream):如FileWriteStream,用于向文件中写入数据。 2. 创建和打开文件流 首先,创建或打开一个文件流需要指定文件路径以及访问模式。下面是一个创建并打开一个文件进行写入操作的例子: csharp using System; using System.IO; class Program { static void Main() { // 指定文件路径和访问模式 string filePath = @"C:\Temp\example.txt"; FileMode mode = FileMode.Create; // 创建并打开一个文件流 using FileStream fs = new FileStream(filePath, mode); // 写入数据到文件流 byte[] content = Encoding.UTF8.GetBytes("Hello, File Stream!"); fs.Write(content, 0, content.Length); Console.WriteLine($"Data written to file: {filePath}"); } } 上述代码首先定义了文件路径和访问模式,然后创建了一个FileStream对象。这里使用FileMode.Create表示如果文件不存在则创建,存在则覆盖原有内容。接着,我们将字符串转换为字节数组并写入文件流。 3. 文件流的读取操作 读取文件流的操作同样直观易懂。以下是一个读取文本文件并将内容打印到控制台的例子: csharp static void ReadFileStream(string filePath) { using FileStream fs = new FileStream(filePath, FileMode.Open); using StreamReader reader = new StreamReader(fs, Encoding.UTF8); // 读取文件内容 string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); // 这里可以添加其他处理逻辑,例如解析或分析文件内容 } } 在这个示例中,我们打开了一个已存在的文件流,并通过StreamReader逐行读取其中的内容。这在处理配置文件、日志文件等场景非常常见。 4. 文件流的高级应用与注意事项 文件流在处理大文件时尤为高效,因为它允许我们按块或按需读取或写入数据,而非一次性加载整个文件。但同时,也需要注意以下几个关键点: - 资源管理:务必使用using语句确保流在使用完毕后能及时关闭,避免资源泄漏。 - 异常处理:在文件流操作中,可能会遇到各种IO错误,如文件不存在、权限不足等,因此要合理捕获和处理这些异常。 - 缓冲区大小的选择:根据实际情况调整缓冲区大小,可以显著提高读写效率。 综上所述,C中的文件流处理功能强大而灵活,无论是简单的文本文件操作还是复杂的大数据处理,都能提供稳定且高效的解决方案。在实际操作中,我们得根据业务的具体需要,真正吃透文件流的各种功能特性,并且能够灵活运用到飞起,这样才能让文件流的威力发挥到极致。
2023-05-01 08:51:54
468
岁月静好
Apache Pig
...ache Pig作为Hadoop生态的重要一员,以其SQL-like的脚本语言——Pig Latin,为用户提供了对大规模数据集进行高效处理的能力。然而,在把Pig任务扔给YARN(也就是那个“又一个资源协调器”)集群的时候,咱们时常会碰到个让人头疼的小插曲:这任务竟然没法顺利拿到队列里的资源。本文将深入探讨这个问题的发生原因,并通过实例代码和详细解析来提供有效的解决策略。 2. 问题现象及初步分析 当您尝试提交一个Pig作业到YARN上运行时,可能遇到类似这样的错误提示:“Failed to submit application to YARN: org.apache.hadoop.yarn.exceptions.YarnException: Application submission failed for appattempt_1603984756655_0001 due to queue 'your-queue-name' not existing in the system.” 这个错误明确指出,Pig作业无法在指定的队列中找到足够的资源来执行任务。 问题根源:这通常是因为队列配置不正确或资源管理器未识别出该队列。YARN按照预定义的队列管理和分配资源,如果提交作业时不明确指定或指定了不存在的队列名称,就会导致作业无法获取所需的计算资源。 3. 示例代码与问题演示 首先,让我们看一段典型的使用Apache Pig提交作业到YARN的示例代码: shell pig -x mapreduce -param yarn_queue_name=your-queue-name script.pig 假设这里的"your-queue-name"是一个实际不存在于YARN中的队列名,那么上述命令执行后就会出现文章开头所述的错误。 4. 解决方案与步骤 4.1 检查YARN队列配置 第一步是确认YARN资源管理器的队列配置是否包含了你所指定的队列名。登录到Hadoop ResourceManager节点,查看yarn-site.xml文件中的相关配置,如yarn.resourcemanager.scheduler.class和yarn.scheduler.capacity.root.queues等属性,确保目标队列已被正确创建并启用。 4.2 确认权限问题 其次,检查提交作业的用户是否有权访问指定队列。在容量调度器这个系统里,每个队列都有一份专属的“通行证名单”——也就是ACL(访问控制列表)。为了保险起见,得确认一下您是不是已经在这份名单上,拥有对当前队列的访问权限。 4.3 正确指定队列名 在提交Pig作业时,请务必准确无误地指定队列名。例如,如果你在YARN中有名为"data_processing"的队列,应如此提交作业: shell pig -x mapreduce -param yarn_queue_name=data_processing script.pig 4.4 调整资源请求 最后,根据队列的实际资源配置情况,适当调整作业的资源请求(如vCores、内存等)。如果资源请求开得太大,即使队列里明明有资源并且存货充足,作业也可能抓不到自己需要的那份资源,导致无法顺利完成任务。 5. 总结与思考 理解并解决Pig作业在YARN上无法获取队列资源的问题,不仅需要我们熟悉Apache Pig和YARN的工作原理,更要求我们在实践中细心观察、细致排查。当你碰到这类问题的时候,不妨先从最基础的设置开始“摸底”,一步步地往里探索。同时,得保持像猫捉老鼠那样的敏锐眼神和逮住问题不放的耐心,这样你才能在海量数据这座大山中稳稳当当地向前迈进。毕竟,就像生活一样,处理大数据问题的过程也是充满挑战与乐趣的探索之旅。
2023-06-29 10:55:56
473
半夏微凉
转载文章
...t java.io.File;import java.io.FileInputStream;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;import org.htmlparser.Node;import org.htmlparser.NodeFilter;import org.htmlparser.Parser;import org.htmlparser.filters.NodeClassFilter;import org.htmlparser.filters.OrFilter;import org.htmlparser.tags.LinkTag;import org.htmlparser.tags.TableTag;import org.htmlparser.util.NodeList;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;public class HtmlLook {private static String ENCODE = "UTF-8";public static void main(String[] args) {String szContent = openFile( "d:/index.html");try {Document doc = Jsoup.parse(szContent);Elements elList=doc.getElementsByAttributeValue("id","vulDataTable");szContent=elList.outerHtml();Parser parser = Parser.createParser(szContent, ENCODE);NodeFilter[] filters = new NodeFilter[2];filters[0] = new NodeClassFilter(TableTag.class); filters[1] = new NodeClassFilter(LinkTag.class);NodeFilter filter =new OrFilter (filters);NodeList list = parser.extractAllNodesThatMatch(filter);String ldName="";String ldJianjie="";for (int i = 0; i < list.size(); i++) { Node node = list.elementAt(i); if(node instanceof LinkTag){String nodeHtml=node.toHtml();if(nodeHtml.contains("onclick")&&nodeHtml.contains("vul-")){if(!"".equals(ldName)&&!"".equals(ldJianjie)){//提交数据System.out.println("---commit---漏洞名称-------"+ldName);System.out.println("---commit---漏洞简介-------"+ldJianjie);ldName="";ldJianjie="";}String level="";if(nodeHtml.contains("vul-vh")){level="高危漏洞";}else if(nodeHtml.contains("vul-vm")){level="中危漏洞";}else if(nodeHtml.contains("vul-vl")){level="低危漏洞";}ldName=getLinkTagContent(nodeHtml)+"-----"+level+"------";// System.out.println("---漏洞名称-----"+getLinkTagContent(nodeHtml)+"-----"+level+"------");} }else{ldJianjie=getTableTagContent(node.toHtml());} } } catch (Exception e) {e.printStackTrace();} }/ 提取文件里面的文本信息 @param szFileName @return/public static String openFile(String szFileName) {try {BufferedReader bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(szFileName)), ENCODE));String szContent = "";String szTemp;while ((szTemp = bis.readLine()) != null) {szContent += szTemp + "\n";}bis.close();return szContent;} catch (Exception e) {return "";} }/ 提取标签<a>a</a>内的内容 return a;/public static String getLinkTagContent(String link){String content="";Pattern pattern = Pattern.compile("<a[^>]>(.?)</a>");Matcher matcher = pattern.matcher(link);if(matcher.find()){content=matcher.group(1);}return content;}/ 解析Table标签内的东西 @param table/public static String getTableTagContent(String table){Map<String,String> conMap=new HashMap<String,String>();String content="";Document doc = Jsoup.parse(table);Elements elList=doc.getElementsByAttributeValue("class","cmn_table plumb");Element el=elList.first();Elements trLists = el.select("tr");for (int i = 0; i < trLists.size(); i++) {Elements tds = trLists.get(i).select("td");String key="";String val="";for (int j = 0; j < tds.size(); j++) {String text = tds.get(j).text();if(j==0){key=text; }else{val=text; } }conMap.put(key, val);content+="|"+key+"-"+val;// System.out.println(key+"-"+val);}return content;} } 本篇文章为转载内容。原文链接:https://blog.csdn.net/zhaoguoshuai91/article/details/51802116。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-07-19 10:42:16
295
转载
转载文章
...e user profile system, but ASP.NET Identity takes a different approach. 我在第13章创建AppUser类来表示用户时曾做过说明,基类定义了一组描述用户的基本属性,如E-mail地址、电话号码等。大多数应用程序还需要存储用户的更多信息,包括持久化应用程序爱好以及地址等细节——简言之,需要存储对运行应用程序有用并且在各次会话之间应当保持的任何数据。在ASP.NET Membership中,这是通过用户资料(User Profile)系统来处理的,但ASP.NET Identity采取了一种不同的办法。 Because the ASP.NET Identity system uses Entity Framework to store its data by default, defining additional user information is just a matter of adding properties to the user class and letting the Code First feature create the database schema required to store them. Table 15-3 puts custom user properties in context. 因为ASP.NET Identity默认是使用Entity Framework来存储其数据的,定义附加的用户信息只不过是给用户类添加属性的事情,然后让Code First特性去创建需要存储它们的数据库架构即可。表15-3描述了自定义用户属性的情形。 Table 15-3. Putting Cusotm User Properties in Context 表15-3. 自定义用户属性的情形 Question 问题 Answer 回答 What is it? 什么是自定义用户属性? Custom user properties allow you to store additional information about your users, including their preferences and settings. 自定义用户属性让你能够存储附加的用户信息,包括他们的爱好和设置。 Why should I care? 为何要关心它? A persistent store of settings means that the user doesn’t have to provide the same information each time they log in to the application. 设置的持久化存储意味着,用户不必每次登录到应用程序时都提供同样的信息。 How is it used by the MVC framework? 在MVC框架中如何使用它? This feature isn’t used directly by the MVC framework, but it is available for use in action methods. 此特性不是由MVC框架直接使用的,但它在动作方法中使用是有效的。 15.2.1 Defining Custom Properties 15.2.1 定义自定义属性 Listing 15-1 shows how I added a simple property to the AppUser class to represent the city in which the user lives. 清单15-1演示了如何给AppUser类添加一个简单的属性,用以表示用户生活的城市。 Listing 15-1. Adding a Property in the AppUser.cs File 清单15-1. 在AppUser.cs文件中添加属性 using System;using Microsoft.AspNet.Identity.EntityFramework;namespace Users.Models { public enum Cities {LONDON, PARIS, CHICAGO}public class AppUser : IdentityUser {public Cities City { get; set; } }} I have defined an enumeration called Cities that defines values for some large cities and added a property called City to the AppUser class. To allow the user to view and edit their City property, I added actions to the Home controller, as shown in Listing 15-2. 这里定义了一个枚举,名称为Cities,它定义了一些大城市的值,另外给AppUser类添加了一个名称为City的属性。为了让用户能够查看和编辑City属性,给Home控制器添加了几个动作方法,如清单15-2所示。 Listing 15-2. Adding Support for Custom User Properties in the HomeController.cs File 清单15-2. 在HomeController.cs文件中添加对自定义属性的支持 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models;namespace Users.Controllers {public class HomeController : Controller {[Authorize]public ActionResult Index() {return View(GetData("Index"));}[Authorize(Roles = "Users")]public ActionResult OtherAction() {return View("Index", GetData("OtherAction"));}private Dictionary<string, object> GetData(string actionName) {Dictionary<string, object> dict= new Dictionary<string, object>();dict.Add("Action", actionName);dict.Add("User", HttpContext.User.Identity.Name);dict.Add("Authenticated", HttpContext.User.Identity.IsAuthenticated);dict.Add("Auth Type", HttpContext.User.Identity.AuthenticationType);dict.Add("In Users Role", HttpContext.User.IsInRole("Users"));return dict;} [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;await UserManager.UpdateAsync(user);return View(user);}private AppUser CurrentUser {get {return UserManager.FindByName(HttpContext.User.Identity.Name);} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } I added a CurrentUser property that uses the AppUserManager class to retrieve an AppUser instance to represent the current user. I pass the AppUser object as the view model object in the GET version of the UserProps action method, and the POST method uses it to update the value of the new City property. Listing 15-3 shows the UserProps.cshtml view, which displays the City property value and contains a form to change it. 我添加了一个CurrentUser属性,它使用AppUserManager类接收了表示当前用户的AppUser实例。在GET版本的UserProps动作方法中,传递了这个AppUser对象作为视图模型。而在POST版的方法中用它更新了City属性的值。清单15-3显示了UserProps.cshtml视图,它显示了City属性的值,并包含一个修改它的表单。 Listing 15-3. The Contents of the UserProps.cshtml File in the Views/Home Folder 清单15-3. Views/Home文件夹中UserProps.cshtml文件的内容 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";}<div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr></table></div> @using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Caution Don’t start the application when you have created the view. In the sections that follow, I demonstrate how to preserve the contents of the database, and if you start the application now, the ASP.NET Identity users will be deleted. 警告:创建了视图之后不要启动应用程序。在以下小节中,将演示如何保留数据库的内容,如果现在启动应用程序,将会删除ASP.NET Identity的用户。 15.2.2 Preparing for Database Migration 15.2.2 准备数据库迁移 The default behavior for the Entity Framework Code First feature is to drop the tables in the database and re-create them whenever classes that drive the schema have changed. You saw this in Chapter 14 when I added support for roles: When the application was started, the database was reset, and the user accounts were lost. Entity Framework Code First特性的默认行为是,一旦修改了派生数据库架构的类,便会删除数据库中的数据表,并重新创建它们。在第14章可以看到这种情况,在我添加角色支持时:当重启应用程序后,数据库被重置,用户账号也丢失。 Don’t start the application yet, but if you were to do so, you would see a similar effect. Deleting data during development is usually not a problem, but doing so in a production setting is usually disastrous because it deletes all of the real user accounts and causes a panic while the backups are restored. In this section, I am going to demonstrate how to use the database migration feature, which updates a Code First schema in a less brutal manner and preserves the existing data it contains. 不要启动应用程序,但如果你这么做了,会看到类似的效果。在开发期间删除数据没什么问题,但如果在产品设置中这么做了,通常是灾难性的,因为它会删除所有真实的用户账号,而备份恢复是很痛苦的事。在本小节中,我打算演示如何使用数据库迁移特性,它能以比较温和的方式更新Code First的架构,并保留架构中的已有数据。 The first step is to issue the following command in the Visual Studio Package Manager Console: 第一个步骤是在Visual Studio的“Package Manager Console(包管理器控制台)”中发布以下命令: Enable-Migrations –EnableAutomaticMigrations This enables the database migration support and creates a Migrations folder in the Solution Explorer that contains a Configuration.cs class file, the contents of which are shown in Listing 15-4. 它启用了数据库的迁移支持,并在“Solution Explorer(解决方案资源管理器)”创建一个Migrations文件夹,其中含有一个Configuration.cs类文件,内容如清单15-4所示。 Listing 15-4. The Contents of the Configuration.cs File 清单15-4. Configuration.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity;using System.Data.Entity.Migrations;using System.Linq;internal sealed class Configuration: DbMigrationsConfiguration<Users.Infrastructure.AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(Users.Infrastructure.AppIdentityDbContext context) {// This method will be called after migrating to the latest version.// 此方法将在迁移到最新版本时调用// You can use the DbSet<T>.AddOrUpdate() helper extension method// to avoid creating duplicate seed data. E.g.// 例如,你可以使用DbSet<T>.AddOrUpdate()辅助器方法来避免创建重复的种子数据//// context.People.AddOrUpdate(// p => p.FullName,// new Person { FullName = "Andrew Peters" },// new Person { FullName = "Brice Lambson" },// new Person { FullName = "Rowan Miller" }// );//} }} Tip You might be wondering why you are entering a database migration command into the console used to manage NuGet packages. The answer is that the Package Manager Console is really PowerShell, which is a general-purpose tool that is mislabeled by Visual Studio. You can use the console to issue a wide range of helpful commands. See http://go.microsoft.com/fwlink/?LinkID=108518 for details. 提示:你可能会觉得奇怪,为什么要在管理NuGet包的控制台中输入数据库迁移的命令?答案是“Package Manager Console(包管理控制台)”是真正的PowerShell,这是Visual studio冒用的一个通用工具。你可以使用此控制台发送大量的有用命令,详见http://go.microsoft.com/fwlink/?LinkID=108518。 The class will be used to migrate existing content in the database to the new schema, and the Seed method will be called to provide an opportunity to update the existing database records. In Listing 15-5, you can see how I have used the Seed method to set a default value for the new City property I added to the AppUser class. (I have also updated the class file to reflect my usual coding style.) 这个类将用于把数据库中的现有内容迁移到新的数据库架构,Seed方法的调用为更新现有数据库记录提供了机会。在清单15-5中可以看到,我如何用Seed方法为新的City属性设置默认值,City是添加到AppUser类中自定义属性。(为了体现我一贯的编码风格,我对这个类文件也进行了更新。) Listing 15-5. Managing Existing Content in the Configuration.cs File 清单15-5. 在Configuration.cs文件中管理已有内容 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models;namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);}foreach (AppUser dbUser in userMgr.Users) {dbUser.City = Cities.PARIS;}context.SaveChanges();} }} You will notice that much of the code that I added to the Seed method is taken from the IdentityDbInit class, which I used to seed the database with an administration user in Chapter 14. This is because the new Configuration class added to support database migrations will replace the seeding function of the IdentityDbInit class, which I’ll update shortly. Aside from ensuring that there is an admin user, the statements in the Seed method that are important are the ones that set the initial value for the City property I added to the AppUser class, as follows: 你可能会注意到,添加到Seed方法中的许多代码取自于IdentityDbInit类,在第14章中我用这个类将管理用户植入了数据库。这是因为这个新添加的、用以支持数据库迁移的Configuration类,将代替IdentityDbInit类的种植功能,我很快便会更新这个类。除了要确保有admin用户之外,在Seed方法中的重要语句是那些为AppUser类的City属性设置初值的语句,如下所示: ...foreach (AppUser dbUser in userMgr.Users) { dbUser.City = Cities.PARIS;}context.SaveChanges();... You don’t have to set a default value for new properties—I just wanted to demonstrate that the Seed method in the Configuration class can be used to update the existing user records in the database. 你不一定要为新属性设置默认值——这里只是想演示Configuration类中的Seed方法,可以用它更新数据库中的已有用户记录。 Caution Be careful when setting values for properties in the Seed method for real projects because the values will be applied every time you change the schema, overriding any values that the user has set since the last schema update was performed. I set the value of the City property just to demonstrate that it can be done. 警告:在用于真实项目的Seed方法中为属性设置值时要小心,因为你每一次修改架构时,都会运用这些值,这会将自执行上一次架构更新之后,用户设置的任何数据覆盖掉。这里设置City属性的值只是为了演示它能够这么做。 Changing the Database Context Class 修改数据库上下文类 The reason that I added the seeding code to the Configuration class is that I need to change the IdentityDbInit class. At present, the IdentityDbInit class is derived from the descriptively named DropCreateDatabaseIfModelChanges<AppIdentityDbContext> class, which, as you might imagine, drops the entire database when the Code First classes change. Listing 15-6 shows the changes I made to the IdentityDbInit class to prevent it from affecting the database. 在Configuration类中添加种植代码的原因是我需要修改IdentityDbInit类。此时,IdentityDbInit类派生于描述性命名的DropCreateDatabaseIfModelChanges<AppIdentityDbContext> 类,和你相像的一样,它会在Code First类改变时删除整个数据库。清单15-6显示了我对IdentityDbInit类所做的修改,以防止它影响数据库。 Listing 15-6. Preventing Database Schema Changes in the AppIdentityDbContext.cs File 清单15-6. 在AppIdentityDbContext.cs文件是阻止数据库架构变化 using System.Data.Entity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Models;using Microsoft.AspNet.Identity; namespace Users.Infrastructure {public class AppIdentityDbContext : IdentityDbContext<AppUser> {public AppIdentityDbContext() : base("IdentityDb") { }static AppIdentityDbContext() {Database.SetInitializer<AppIdentityDbContext>(new IdentityDbInit());}public static AppIdentityDbContext Create() {return new AppIdentityDbContext();} } public class IdentityDbInit : NullDatabaseInitializer<AppIdentityDbContext> {} } I have removed the methods defined by the class and changed its base to NullDatabaseInitializer<AppIdentityDbContext> , which prevents the schema from being altered. 我删除了这个类中所定义的方法,并将它的基类改为NullDatabaseInitializer<AppIdentityDbContext> ,它可以防止架构修改。 15.2.3 Performing the Migration 15.2.3 执行迁移 All that remains is to generate and apply the migration. First, run the following command in the Package Manager Console: 剩下的事情只是生成并运用迁移了。首先,在“Package Manager Console(包管理器控制台)”中执行以下命令: Add-Migration CityProperty This creates a new migration called CityProperty (I like my migration names to reflect the changes I made). A class new file will be added to the Migrations folder, and its name reflects the time at which the command was run and the name of the migration. My file is called 201402262244036_CityProperty.cs, for example. The contents of this file contain the details of how Entity Framework will change the database during the migration, as shown in Listing 15-7. 这创建了一个名称为CityProperty的新迁移(我比较喜欢让迁移的名称反映出我所做的修改)。这会在文件夹中添加一个新的类文件,而且其命名会反映出该命令执行的时间以及迁移名称,例如,我的这个文件名称为201402262244036_CityProperty.cs。该文件的内容含有迁移期间Entity Framework修改数据库的细节,如清单15-7所示。 Listing 15-7. The Contents of the 201402262244036_CityProperty.cs File 清单15-7. 201402262244036_CityProperty.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity.Migrations; public partial class Init : DbMigration {public override void Up() {AddColumn("dbo.AspNetUsers", "City", c => c.Int(nullable: false));}public override void Down() {DropColumn("dbo.AspNetUsers", "City");} }} The Up method describes the changes that have to be made to the schema when the database is upgraded, which in this case means adding a City column to the AspNetUsers table, which is the one that is used to store user records in the ASP.NET Identity database. Up方法描述了在数据库升级时,需要对架构所做的修改,在这个例子中,意味着要在AspNetUsers数据表中添加City数据列,该数据表是ASP.NET Identity数据库用来存储用户记录的。 The final step is to perform the migration. Without starting the application, run the following command in the Package Manager Console: 最后一步是执行迁移。无需启动应用程序,只需在“Package Manager Console(包管理器控制台)”中运行以下命令即可: Update-Database –TargetMigration CityProperty The database schema will be modified, and the code in the Configuration.Seed method will be executed. The existing user accounts will have been preserved and enhanced with a City property (which I set to Paris in the Seed method). 这会修改数据库架构,并执行Configuration.Seed方法中的代码。已有用户账号会被保留,且增强了City属性(我在Seed方法中已将其设置为“Paris”)。 15.2.4 Testing the Migration 15.2.4 测试迁移 To test the effect of the migration, start the application, navigate to the /Home/UserProps URL, and authenticate as one of the Identity users (for example, as Alice with the password MySecret). Once authenticated, you will see the current value of the City property for the user and have the opportunity to change it, as shown in Figure 15-3. 为了测试迁移的效果,启动应用程序,导航到/Home/UserProps URL,并以Identity中的用户(例如Alice,口令MySecret)进行认证。一旦已被认证,便会看到该用户City属性的当前值,并可以对其进行修改,如图15-3所示。 Figure 15-3. Displaying and changing a custom user property 图15-3. 显示和个性自定义用户属性 15.2.5 Defining an Additional Property 15.2.5 定义附加属性 Now that database migrations are set up, I am going to define a further property just to demonstrate how subsequent changes are handled and to show a more useful (and less dangerous) example of using the Configuration.Seed method. Listing 15-8 shows how I added a Country property to the AppUser class. 现在,已经建立了数据库迁移,我打算再定义一个属性,这恰恰演示了如何处理持续不断的修改,也为了演示Configuration.Seed方法更有用(至少无害)的示例。清单15-8显示了我在AppUser类上添加了一个Country属性。 Listing 15-8. Adding Another Property in the AppUserModels.cs File 清单15-8. 在AppUserModels.cs文件中添加另一个属性 using System;using Microsoft.AspNet.Identity.EntityFramework; namespace Users.Models {public enum Cities {LONDON, PARIS, CHICAGO} public enum Countries {NONE, UK, FRANCE, USA}public class AppUser : IdentityUser {public Cities City { get; set; }public Countries Country { get; set; }public void SetCountryFromCity(Cities city) {switch (city) {case Cities.LONDON:Country = Countries.UK;break;case Cities.PARIS:Country = Countries.FRANCE;break;case Cities.CHICAGO:Country = Countries.USA;break;default:Country = Countries.NONE;break;} }} } I have added an enumeration to define the country names and a helper method that selects a country value based on the City property. Listing 15-9 shows the change I made to the Configuration class so that the Seed method sets the Country property based on the City, but only if the value of Country is NONE (which it will be for all users when the database is migrated because the Entity Framework sets enumeration columns to the first value). 我已经添加了一个枚举,它定义了国家名称。还添加了一个辅助器方法,它可以根据City属性选择一个国家。清单15-9显示了对Configuration类所做的修改,以使Seed方法根据City设置Country属性,但只当Country为NONE时才进行设置(在迁移数据库时,所有用户都是NONE,因为Entity Framework会将枚举列设置为枚举的第一个值)。 Listing 15-9. Modifying the Database Seed in the Configuration.cs File 清单15-9. 在Configuration.cs文件中修改数据库种子 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models; namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);} foreach (AppUser dbUser in userMgr.Users) {if (dbUser.Country == Countries.NONE) {dbUser.SetCountryFromCity(dbUser.City);} }context.SaveChanges();} }} This kind of seeding is more useful in a real project because it will set a value for the Country property only if one has not already been set—subsequent migrations won’t be affected, and user selections won’t be lost. 这种种植在实际项目中会更有用,因为它只会在Country属性未设置时,才会设置Country属性的值——后继的迁移不会受到影响,因此不会失去用户的选择。 1. Adding Application Support 1. 添加应用程序支持 There is no point defining additional user properties if they are not available in the application, so Listing 15-10 shows the change I made to the Views/Home/UserProps.cshtml file to display the value of the Country property. 应用程序中如果没有定义附加属性的地方,则附加属性就无法使用了,因此,清单15-10显示了我对Views/Home/UserProps.cshtml文件的修改,以显示Country属性的值。 Listing 15-10. Displaying an Additional Property in the UserProps.cshtml File 清单15-10. 在UserProps.cshtml文件中显示附加属性 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";} <div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr> <tr><th>Country</th><td>@Model.Country</td></tr></table></div>@using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Listing 15-11 shows the corresponding change I made to the Home controller to update the Country property when the City value changes. 为了在City值变化时能够更新Country属性,清单15-11显示了我对Home控制器所做的相应修改。 Listing 15-11. Setting Custom Properties in the HomeController.cs File 清单15-11. 在HomeController.cs文件中设置自定义属性 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models; namespace Users.Controllers {public class HomeController : Controller {// ...other action methods omitted for brevity...// ...出于简化,这里忽略了其他动作方法... [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;user.SetCountryFromCity(city);await UserManager.UpdateAsync(user);return View(user);}// ...properties omitted for brevity...// ...出于简化,这里忽略了一些属性...} } 2. Performing the Migration 2. 准备迁移 All that remains is to create and apply a new migration. Enter the following command into the Package Manager Console: 剩下的事情就是创建和运用新的迁移了。在“Package Manager Console(包管理器控制台)”中输入以下命令: Add-Migration CountryProperty This will generate another file in the Migrations folder that contains the instruction to add the Country column. To apply the migration, execute the following command: 这将在Migrations文件夹中生成另一个文件,它含有添加Country数据表列的指令。为了运用迁移,可执行以下命令: Update-Database –TargetMigration CountryProperty The migration will be performed, and the value of the Country property will be set based on the value of the existing City property for each user. You can check the new user property by starting the application and authenticating and navigating to the /Home/UserProps URL, as shown in Figure 15-4. 这将执行迁移,Country属性的值将根据每个用户当前的City属性进行设置。通过启动应用程序,认证并导航到/Home/UserProps URL,便可以查看新的用户属性,如图15-4所示。 Figure 15-4. Creating an additional user property 图15-4. 创建附加用户属性 Tip Although I am focused on the process of upgrading the database, you can also migrate back to a previous version by specifying an earlier migration. Use the –Force argument make changes that cause data loss, such as removing a column. 提示:虽然我们关注了升级数据库的过程,但你也可以回退到以前的版本,只需指定一个早期的迁移即可。使用-Force参数进行修改,会引起数据丢失,例如删除数据表列。 15.3 Working with Claims 15.3 使用声明(Claims) In older user-management systems, such as ASP.NET Membership, the application was assumed to be the authoritative source of all information about the user, essentially treating the application as a closed world and trusting the data that is contained within it. 在旧的用户管理系统中,例如ASP.NET Membership,应用程序被假设成是用户所有信息的权威来源,本质上将应用程序视为是一个封闭的世界,并且只信任其中所包含的数据。 This is such an ingrained approach to software development that it can be hard to recognize that’s what is happening, but you saw an example of the closed-world technique in Chapter 14 when I authenticated users against the credentials stored in the database and granted access based on the roles associated with those credentials. I did the same thing again in this chapter when I added properties to the user class. Every piece of information that I needed to manage user authentication and authorization came from within my application—and that is a perfectly satisfactory approach for many web applications, which is why I demonstrated these techniques in such depth. 这是软件开发的一种根深蒂固的方法,使人很难认识到这到底意味着什么,第14章你已看到了这种封闭世界技术的例子,根据存储在数据库中的凭据来认证用户,并根据与凭据关联在一起的角色来授权访问。本章前述在用户类上添加属性,也做了同样的事情。我管理用户认证与授权所需的每一个数据片段都来自于我的应用程序——而且这是许多Web应用程序都相当满意的一种方法,这也是我如此深入地演示这些技术的原因。 ASP.NET Identity also supports an alternative approach for dealing with users, which works well when the MVC framework application isn’t the sole source of information about users and which can be used to authorize users in more flexible and fluid ways than traditional roles allow. ASP.NET Identity还支持另一种处理用户的办法,当MVC框架的应用程序不是有关用户的唯一信息源时,这种办法会工作得很好,而且能够比传统的角色授权更为灵活且流畅的方式进行授权。 This alternative approach uses claims, and in this section I’ll describe how ASP.NET Identity supports claims-based authorization. Table 15-4 puts claims in context. 这种可选的办法使用了“Claims(声明)”,因此在本小节中,我将描述ASP.NET Identity如何支持“Claims-Based Authorization(基于声明的授权)”。表15-4描述了声明(Claims)的情形。 提示:“Claim”在英文字典中不完全是“声明”的意思,根据本文的描述,感觉把它说成“声明”也不一定合适,所以在之后的译文中基本都写成中英文并用的形式,即“声明(Claims)”。根据表15-4中的声明(Claims)的定义:声明(Claims)是关于用户的一些信息片段。一个用户的信息片段当然有很多,每一个信息片段就是一项声明(Claim),用户的所有信息片段合起来就是该用户的声明(Claims)。请读者注意该单词的单复数形式——译者注 Table 15-4. Putting Claims in Context 表15-4. 声明(Claims)的情形 Question 问题 Answer 答案 What is it? 什么是声明(Claims)? Claims are pieces of information about users that you can use to make authorization decisions. Claims can be obtained from external systems as well as from the local Identity database. 声明(Claims)是关于用户的一些信息片段,可以用它们做出授权决定。声明(Claims)可以从外部系统获取,也可以从本地的Identity数据库获取。 Why should I care? 为何要关心它? Claims can be used to flexibly authorize access to action methods. Unlike conventional roles, claims allow access to be driven by the information that describes the user. 声明(Claims)可以用来对动作方法进行灵活的授权访问。与传统的角色不同,声明(Claims)让访问能够由描述用户的信息进行驱动。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework, but it is integrated into the standard authorization features, such as the Authorize attribute. 这不是直接由MVC框架使用的特性,但它集成到了标准的授权特性之中,例如Authorize注解属性。 Tip you don’t have to use claims in your applications, and as Chapter 14 showed, ASP.NET Identity is perfectly happy providing an application with the authentication and authorization services without any need to understand claims at all. 提示:你在应用程序中不一定要使用声明(Claims),正如第14章所展示的那样,ASP.NET Identity能够为应用程序提供充分的认证与授权服务,而根本不需要理解声明(Claims)。 15.3.1 Understanding Claims 15.3.1 理解声明(Claims) A claim is a piece of information about the user, along with some information about where the information came from. The easiest way to unpack claims is through some practical demonstrations, without which any discussion becomes too abstract to be truly useful. To get started, I added a Claims controller to the example project, the definition of which you can see in Listing 15-12. 一项声明(Claim)是关于用户的一个信息片段(请注意这个英文单词的单复数形式——译者注),并伴有该片段出自何处的某种信息。揭开声明(Claims)含义最容易的方式是做一些实际演示,任何讨论都会过于抽象根本没有真正的用处。为此,我在示例项目中添加了一个Claims控制器,其定义如清单15-12所示。 Listing 15-12. The Contents of the ClaimsController.cs File 清单15-12. ClaimsController.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} }} } Tip You may feel a little lost as I define the code for this example. Don’t worry about the details for the moment—just stick with it until you see the output from the action method and view that I define. More than anything else, that will help put claims into perspective. 提示:你或许会对我为此例定义的代码感到有点失望。此刻对此细节不必着急——只要稍事忍耐,当看到该动作方法和视图的输出便会明白。尤为重要的是,这有助于洞察声明(Claims)。 You can get the claims associated with a user in different ways. One approach is to use the Claims property defined by the user class, but in this example, I have used the HttpContext.User.Identity property to demonstrate the way that ASP.NET Identity is integrated with the rest of the ASP.NET platform. As I explained in Chapter 13, the HttpContext.User.Identity property returns an implementation of the IIdentity interface, which is a ClaimsIdentity object when working using ASP.NET Identity. The ClaimsIdentity class is defined in the System.Security.Claims namespace, and Table 15-5 shows the members it defines that are relevant to this chapter. 可以通过不同的方式获得与用户相关联的声明(Claims)。方法之一就是使用由用户类定义的Claims属性,但在这个例子中,我使用了HttpContext.User.Identity属性,目的是演示ASP.NET Identity与ASP.NET平台集成的方式(请注意这句话所表示的含义:用户类的Claims属性属于ASP.NET Identity,而HttpContext.User.Identity属性则属于ASP.NET平台。由此可见,ASP.NET Identity已经融合到了ASP.NET平台之中——译者注)。正如第13章所解释的那样,HttpContext.User.Identity属性返回IIdentity的接口实现,当使用ASP.NET Identity时,该实现是一个ClaimsIdentity对象。ClaimsIdentity类是在System.Security.Claims命名空间中定义的,表15-5显示了它所定义的与本章有关的成员。 Table 15-5. The Members Defined by the ClaimsIdentity Class 表15-5. ClaimsIdentity类所定义的成员 Name 名称 Description 描述 Claims Returns an enumeration of Claim objects representing the claims for the user. 返回表示用户声明(Claims)的Claim对象枚举 AddClaim(claim) Adds a claim to the user identity. 给用户添加一个声明(Claim) AddClaims(claims) Adds an enumeration of Claim objects to the user identity. 给用户添加Claim对象的枚举。 HasClaim(predicate) Returns true if the user identity contains a claim that matches the specified predicate. See the “Applying Claims” section for an example predicate. 如果用户含有与指定谓词匹配的声明(Claim)时,返回true。参见“运用声明(Claims)”中的示例谓词 RemoveClaim(claim) Removes a claim from the user identity. 删除用户的声明(Claim)。 Other members are available, but the ones in the table are those that are used most often in web applications, for reason that will become obvious as I demonstrate how claims fit into the wider ASP.NET platform. 还有一些可用的其它成员,但表中的这些是在Web应用程序中最常用的,随着我演示如何将声明(Claims)融入更宽泛的ASP.NET平台,它们为什么最常用就很显然了。 In Listing 15-12, I cast the IIdentity implementation to the ClaimsIdentity type and pass the enumeration of Claim objects returned by the ClaimsIdentity.Claims property to the View method. A Claim object represents a single piece of data about the user, and the Claim class defines the properties shown in Table 15-6. 在清单15-12中,我将IIdentity实现转换成了ClaimsIdentity类型,并且给View方法传递了ClaimsIdentity.Claims属性所返回的Claim对象的枚举。Claim对象所示表示的是关于用户的一个单一的数据片段,Claim类定义的属性如表15-6所示。 Table 15-6. The Properties Defined by the Claim Class 表15-6. Claim类定义的属性 Name 名称 Description 描述 Issuer Returns the name of the system that provided the claim 返回提供声明(Claim)的系统名称 Subject Returns the ClaimsIdentity object for the user who the claim refers to 返回声明(Claim)所指用户的ClaimsIdentity对象 Type Returns the type of information that the claim represents 返回声明(Claim)所表示的信息类型 Value Returns the piece of information that the claim represents 返回声明(Claim)所表示的信息片段 Listing 15-13 shows the contents of the Index.cshtml file that I created in the Views/Claims folder and that is rendered by the Index action of the Claims controller. The view adds a row to a table for each claim about the user. 清单15-13显示了我在Views/Claims文件夹中创建的Index.cshtml文件的内容,它由Claims控制器中的Index动作方法进行渲染。该视图为用户的每项声明(Claim)添加了一个表格行。 Listing 15-13. The Contents of the Index.cshtml File in the Views/Claims Folder 清单15-13. Views/Claims文件夹中Index.cshtml文件的内容 @using System.Security.Claims@using Users.Infrastructure@model IEnumerable<Claim>@{ ViewBag.Title = "Claims"; }<div class="panel panel-primary"><div class="panel-heading">Claims</div><table class="table table-striped"><tr><th>Subject</th><th>Issuer</th><th>Type</th><th>Value</th></tr>@foreach (Claim claim in Model.OrderBy(x => x.Type)) {<tr><td>@claim.Subject.Name</td><td>@claim.Issuer</td><td>@Html.ClaimType(claim.Type)</td><td>@claim.Value</td></tr>}</table></div> The value of the Claim.Type property is a URI for a Microsoft schema, which isn’t especially useful. The popular schemas are used as the values for fields in the System.Security.Claims.ClaimTypes class, so to make the output from the Index.cshtml view easier to read, I added an HTML helper to the IdentityHelpers.cs file, as shown in Listing 15-14. It is this helper that I use in the Index.cshtml file to format the value of the Claim.Type property. Claim.Type属性的值是一个微软模式(Microsoft Schema)的URI(统一资源标识符),这是特别有用的。System.Security.Claims.ClaimTypes类中字段的值使用的是流行模式(Popular Schema),因此为了使Index.cshtml视图的输出更易于阅读,我在IdentityHelpers.cs文件中添加了一个HTML辅助器,如清单15-14所示。Index.cshtml文件正是使用这个辅助器格式化了Claim.Type属性的值。 Listing 15-14. Adding a Helper to the IdentityHelpers.cs File 清单15-14. 在IdentityHelpers.cs文件中添加辅助器 using System.Web;using System.Web.Mvc;using Microsoft.AspNet.Identity.Owin;using System;using System.Linq;using System.Reflection;using System.Security.Claims;namespace Users.Infrastructure {public static class IdentityHelpers {public static MvcHtmlString GetUserName(this HtmlHelper html, string id) {AppUserManager mgr= HttpContext.Current.GetOwinContext().GetUserManager<AppUserManager>();return new MvcHtmlString(mgr.FindByIdAsync(id).Result.UserName);} public static MvcHtmlString ClaimType(this HtmlHelper html, string claimType) {FieldInfo[] fields = typeof(ClaimTypes).GetFields();foreach (FieldInfo field in fields) {if (field.GetValue(null).ToString() == claimType) {return new MvcHtmlString(field.Name);} }return new MvcHtmlString(string.Format("{0}",claimType.Split('/', '.').Last()));} }} Note The helper method isn’t at all efficient because it reflects on the fields of the ClaimType class for each claim that is displayed, but it is sufficient for my purposes in this chapter. You won’t often need to display the claim type in real applications. 注:该辅助器并非十分有效,因为它只是针对每个要显示的声明(Claim)映射出ClaimType类的字段,但对我要的目的已经足够了。在实际项目中不会经常需要显示声明(Claim)的类型。 To see why I have created a controller that uses claims without really explaining what they are, start the application, authenticate as the user Alice (with the password MySecret), and request the /Claims/Index URL. Figure 15-5 shows the content that is generated. 为了弄明白我为何要先创建一个使用声明(Claims)的控制器,而没有真正解释声明(Claims)是什么的原因,可以启动应用程序,以用户Alice进行认证(其口令是MySecret),并请求/Claims/Index URL。图15-5显示了生成的内容。 Figure 15-5. The output from the Index action of the Claims controller 图15-5. Claims控制器中Index动作的输出 It can be hard to make out the detail in the figure, so I have reproduced the content in Table 15-7. 这可能还难以认识到此图的细节,为此我在表15-7中重列了其内容。 Table 15-7. The Data Shown in Figure 15-5 表15-7. 图15-5中显示的数据 Subject(科目) Issuer(发行者) Type(类型) Value(值) Alice LOCAL AUTHORITY SecurityStamp Unique ID Alice LOCAL AUTHORITY IdentityProvider ASP.NET Identity Alice LOCAL AUTHORITY Role Employees Alice LOCAL AUTHORITY Role Users Alice LOCAL AUTHORITY Name Alice Alice LOCAL AUTHORITY NameIdentifier Alice’s user ID The table shows the most important aspect of claims, which is that I have already been using them when I implemented the traditional authentication and authorization features in Chapter 14. You can see that some of the claims relate to user identity (the Name claim is Alice, and the NameIdentifier claim is Alice’s unique user ID in my ASP.NET Identity database). 此表展示了声明(Claims)最重要的方面,这些是我在第14章中实现传统的认证和授权特性时,一直在使用的信息。可以看出,有些声明(Claims)与用户标识有关(Name声明是Alice,NameIdentifier声明是Alice在ASP.NET Identity数据库中的唯一用户ID号)。 Other claims show membership of roles—there are two Role claims in the table, reflecting the fact that Alice is assigned to both the Users and Employees roles. There is also a claim about how Alice has been authenticated: The IdentityProvider is set to ASP.NET Identity. 其他声明(Claims)显示了角色成员——表中有两个Role声明(Claim),体现出Alice被赋予了Users和Employees两个角色这一事实。还有一个是Alice已被认证的声明(Claim):IdentityProvider被设置到了ASP.NET Identity。 The difference when this information is expressed as a set of claims is that you can determine where the data came from. The Issuer property for all the claims shown in the table is set to LOCAL AUTHORITY, which indicates that the user’s identity has been established by the application. 当这种信息被表示成一组声明(Claims)时的差别是,你能够确定这些数据是从哪里来的。表中所显示的所有声明的Issuer属性(发布者)都被设置到了LOACL AUTHORITY(本地授权),这说明该用户的标识是由应用程序建立的。 So, now that you have seen some example claims, I can more easily describe what a claim is. A claim is any piece of information about a user that is available to the application, including the user’s identity and role memberships. And, as you have seen, the information I have been defining about my users in earlier chapters is automatically made available as claims by ASP.NET Identity. 因此,现在你已经看到了一些声明(Claims)示例,我可以更容易地描述声明(Claim)是什么了。一项声明(Claim)是可用于应用程序中的有关用户的一个信息片段,包括用户的标识以及角色成员等。而且,正如你所看到的,我在前几章定义的关于用户的信息,被ASP.NET Identity自动地作为声明(Claims)了。 15.3.2 Creating and Using Claims 15.3.2 创建和使用声明(Claims) Claims are interesting for two reasons. The first reason is that an application can obtain claims from multiple sources, rather than just relying on a local database for information about the user. You will see a real example of this when I show you how to authenticate users through a third-party system in the “Using Third-Party Authentication” section, but for the moment I am going to add a class to the example project that simulates a system that provides claims information. Listing 15-15 shows the contents of the LocationClaimsProvider.cs file that I added to the Infrastructure folder. 声明(Claims)比较有意思的原因有两个。第一个原因是应用程序可以从多个来源获取声明(Claims),而不是只能依靠本地数据库关于用户的信息。你将会看到一个实际的示例,在“使用第三方认证”小节中,将演示如何通过第三方系统来认证用户。不过,此刻我只打算在示例项目中添加一个类,用以模拟一个提供声明(Claims)信息的系统。清单15-15显示了我添加到Infrastructure文件夹中LocationClaimsProvider.cs文件的内容。 Listing 15-15. The Contents of the LocationClaimsProvider.cs File 清单15-15. LocationClaimsProvider.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public static class LocationClaimsProvider {public static IEnumerable<Claim> GetClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.Name.ToLower() == "alice") {claims.Add(CreateClaim(ClaimTypes.PostalCode, "DC 20500"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "DC"));} else {claims.Add(CreateClaim(ClaimTypes.PostalCode, "NY 10036"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "NY"));}return claims;}private static Claim CreateClaim(string type, string value) {return new Claim(type, value, ClaimValueTypes.String, "RemoteClaims");} }} The GetClaims method takes a ClaimsIdentity argument and uses the Name property to create claims about the user’s ZIP code and state. This class allows me to simulate a system such as a central HR database, which would be the authoritative source of location information about staff, for example. GetClaims方法以ClaimsIdentity为参数,并使用Name属性创建了关于用户ZIP码(邮政编码)和州府的声明(Claims)。上述这个类使我能够模拟一个诸如中心化的HR数据库(人力资源数据库)之类的系统,它可能会成为全体职员的地点信息的权威数据源。 Claims are associated with the user’s identity during the authentication process, and Listing 15-16 shows the changes I made to the Login action method of the Account controller to call the LocationClaimsProvider class. 在认证过程期间,声明(Claims)是与用户标识关联在一起的,清单15-16显示了我对Account控制器中Login动作方法所做的修改,以便调用LocationClaimsProvider类。 Listing 15-16. Associating Claims with a User in the AccountController.cs File 清单15-16. AccountController.cs文件中用户用声明的关联 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... You can see the effect of the location claims by starting the application, authenticating as a user, and requesting the /Claim/Index URL. Figure 15-6 shows the claims for Alice. You may have to sign out and sign back in again to see the change. 为了看看这个地点声明(Claims)的效果,可以启动应用程序,以一个用户进行认证,并请求/Claim/Index URL。图15-6显示了Alice的声明(Claims)。你可能需要退出,然后再次登录才会看到发生的变化。 Figure 15-6. Defining additional claims for users 图15-6. 定义用户的附加声明 Obtaining claims from multiple locations means that the application doesn’t have to duplicate data that is held elsewhere and allows integration of data from external parties. The Claim.Issuer property tells you where a claim originated from, which helps you judge how accurate the data is likely to be and how much weight you should give the data in your application. Location data obtained from a central HR database is likely to be more accurate and trustworthy than data obtained from an external mailing list provider, for example. 从多个地点获取声明(Claims)意味着应用程序不必复制其他地方保持的数据,并且能够与外部的数据集成。Claim.Issuer属性(图15-6中的Issuer数据列——译者注)能够告诉你一个声明(Claim)的发源地,这有助于让你判断数据的精确程度,也有助于让你决定这类数据在应用程序中的权重。例如,从中心化的HR数据库获取的地点数据可能要比外部邮件列表提供器获取的数据更为精确和可信。 1. Applying Claims 1. 运用声明(Claims) The second reason that claims are interesting is that you can use them to manage user access to your application more flexibly than with standard roles. The problem with roles is that they are static, and once a user has been assigned to a role, the user remains a member until explicitly removed. This is, for example, how long-term employees of big corporations end up with incredible access to internal systems: They are assigned the roles they require for each new job they get, but the old roles are rarely removed. (The unexpectedly broad systems access sometimes becomes apparent during the investigation into how someone was able to ship the contents of the warehouse to their home address—true story.) 声明(Claims)有意思的第二个原因是,你可以用它们来管理用户对应用程序的访问,这要比标准的角色管理更为灵活。角色的问题在于它们是静态的,而且一旦用户已经被赋予了一个角色,该用户便是一个成员,直到明确地删除为止。例如,这意味着大公司的长期雇员,对内部系统的访问会十分惊人:他们每次在获得新工作时,都会赋予所需的角色,但旧角色很少被删除。(在调查某人为何能够将仓库里的东西发往他的家庭地址过程中发现,有时会出现异常宽泛的系统访问——真实的故事) Claims can be used to authorize users based directly on the information that is known about them, which ensures that the authorization changes when the data changes. The simplest way to do this is to generate Role claims based on user data that are then used by controllers to restrict access to action methods. Listing 15-17 shows the contents of the ClaimsRoles.cs file that I added to the Infrastructure. 声明(Claims)可以直接根据用户已知的信息对用户进行授权,这能够保证当数据发生变化时,授权也随之而变。此事最简单的做法是根据用户数据来生成Role声明(Claim),然后由控制器用来限制对动作方法的访问。清单15-17显示了我添加到Infrastructure中的ClaimsRoles.cs文件的内容。 Listing 15-17. The Contents of the ClaimsRoles.cs File 清单15-17. ClaimsRoles.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public class ClaimsRoles {public static IEnumerable<Claim> CreateRolesFromClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.HasClaim(x => x.Type == ClaimTypes.StateOrProvince&& x.Issuer == "RemoteClaims" && x.Value == "DC")&& user.HasClaim(x => x.Type == ClaimTypes.Role&& x.Value == "Employees")) {claims.Add(new Claim(ClaimTypes.Role, "DCStaff"));}return claims;} }} The gnarly looking CreateRolesFromClaims method uses lambda expressions to determine whether the user has a StateOrProvince claim from the RemoteClaims issuer with a value of DC and a Role claim with a value of Employees. If the user has both claims, then a Role claim is returned for the DCStaff role. Listing 15-18 shows how I call the CreateRolesFromClaims method from the Login action in the Account controller. CreateRolesFromClaims是一个粗糙的考察方法,它使用了Lambda表达式,以检查用户是否具有StateOrProvince声明(Claim),该声明来自于RemoteClaims发行者(Issuer),值为DC。也检查用户是否具有Role声明(Claim),其值为Employees。如果用户这两个声明都有,那么便返回一个DCStaff角色的Role声明。清单15-18显示了如何在Account控制器中的Login动作中调用CreateRolesFromClaims方法。 Listing 15-18. Generating Roles Based on Claims in the AccountController.cs File 清单15-18. 在AccountController.cs中根据声明生成角色 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(LocationClaimsProvider.GetClaims(ident)); ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... I can then restrict access to an action method based on membership of the DCStaff role. Listing 15-19 shows a new action method I added to the Claims controller to which I have applied the Authorize attribute. 然后我可以根据DCStaff角色的成员,来限制对一个动作方法的访问。清单15-19显示了在Claims控制器中添加的一个新的动作方法,在该方法上已经运用了Authorize注解属性。 Listing 15-19. Adding a New Action Method to the ClaimsController.cs File 清单15-19. 在ClaimsController.cs文件中添加一个新的动作方法 using System.Security.Claims;using System.Web;using System.Web.Mvc;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [Authorize(Roles="DCStaff")]public string OtherAction() {return "This is the protected action";} }} Users will be able to access OtherAction only if their claims grant them membership to the DCStaff role. Membership of this role is generated dynamically, so a change to the user’s employment status or location information will change their authorization level. 只要用户的声明(Claims)承认他们是DCStaff角色的成员,那么他们便能访问OtherAction动作。该角色的成员是动态生成的,因此,若是用户的雇用状态或地点信息发生变化,也会改变他们的授权等级。 提示:请读者从这个例子中吸取其中的思想精髓。对于读物的理解程度,仁者见仁,智者见智,能领悟多少,全凭各人,译者感觉这里的思想有无数的可能。举例说明:(1)可以根据用户的身份进行授权,比如学生在校时是“学生”,毕业后便是“校友”;(2)可以根据用户所处的部门进行授权,人事部用户属于人事团队,销售部用户属于销售团队,各团队有其自己的应用;(3)下一小节的示例是根据用户的地点授权。简言之:一方面用户的各种声明(Claim)都可以用来进行授权;另一方面用户的声明(Claim)又是可以自定义的。于是可能的运用就无法估计了。总之一句话,这种基于声明的授权(Claims-Based Authorization)有无限可能!要是没有我这里的提示,是否所有读者在此处都会有所体会?——译者注 15.3.3 Authorizing Access Using Claims 15.3.3 使用声明(Claims)授权访问 The previous example is an effective demonstration of how claims can be used to keep authorizations fresh and accurate, but it is a little indirect because I generate roles based on claims data and then enforce my authorization policy based on the membership of that role. A more direct and flexible approach is to enforce authorization directly by creating a custom authorization filter attribute. Listing 15-20 shows the contents of the ClaimsAccessAttribute.cs file, which I added to the Infrastructure folder and used to create such a filter. 前面的示例有效地演示了如何用声明(Claims)来保持新鲜和准确的授权,但有点不太直接,因为我要根据声明(Claims)数据来生成了角色,然后强制我的授权策略基于角色成员。一个更直接且灵活的办法是直接强制授权,其做法是创建一个自定义的授权过滤器注解属性。清单15-20演示了ClaimsAccessAttribute.cs文件的内容,我将它添加在Infrastructure文件夹中,并用它创建了这种过滤器。 Listing 15-20. The Contents of the ClaimsAccessAttribute.cs File 清单15-20. ClaimsAccessAttribute.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Infrastructure {public class ClaimsAccessAttribute : AuthorizeAttribute {public string Issuer { get; set; }public string ClaimType { get; set; }public string Value { get; set; }protected override bool AuthorizeCore(HttpContextBase context) {return context.User.Identity.IsAuthenticated&& context.User.Identity is ClaimsIdentity&& ((ClaimsIdentity)context.User.Identity).HasClaim(x =>x.Issuer == Issuer && x.Type == ClaimType && x.Value == Value);} }} The attribute I have defined is derived from the AuthorizeAttribute class, which makes it easy to create custom authorization policies in MVC framework applications by overriding the AuthorizeCore method. My implementation grants access if the user is authenticated, the IIdentity implementation is an instance of ClaimsIdentity, and the user has a claim with the issuer, type, and value matching the class properties. Listing 15-21 shows how I applied the attribute to the Claims controller to authorize access to the OtherAction method based on one of the location claims created by the LocationClaimsProvider class. 我所定义的这个注解属性派生于AuthorizeAttribute类,通过重写AuthorizeCore方法,很容易在MVC框架应用程序中创建自定义的授权策略。在这个实现中,若用户是已认证的、其IIdentity实现是一个ClaimsIdentity实例,而且该用户有一个带有issuer、type以及value的声明(Claim),它们与这个类的属性是匹配的,则该用户便是允许访问的。清单15-21显示了如何将这个注解属性运用于Claims控制器,以便根据LocationClaimsProvider类创建的地点声明(Claim),对OtherAction方法进行授权访问。 Listing 15-21. Performing Authorization on Claims in the ClaimsController.cs File 清单15-21. 在ClaimsController.cs文件中执行基于声明的授权 using System.Security.Claims;using System.Web;using System.Web.Mvc;using Users.Infrastructure;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [ClaimsAccess(Issuer="RemoteClaims", ClaimType=ClaimTypes.PostalCode,Value="DC 20500")]public string OtherAction() {return "This is the protected action";} }} My authorization filter ensures that only users whose location claims specify a ZIP code of DC 20500 can invoke the OtherAction method. 这个授权过滤器能够确保只有地点声明(Claim)的邮编为DC 20500的用户才能请求OtherAction方法。 15.4 Using Third-Party Authentication 15.4 使用第三方认证 One of the benefits of a claims-based system such as ASP.NET Identity is that any of the claims can come from an external system, even those that identify the user to the application. This means that other systems can authenticate users on behalf of the application, and ASP.NET Identity builds on this idea to make it simple and easy to add support for authenticating users through third parties such as Microsoft, Google, Facebook, and Twitter. 基于声明的系统,如ASP.NET Identity,的好处之一是任何声明都可以来自于外部系统,即使是将用户标识到应用程序的那些声明。这意味着其他系统可以代表应用程序来认证用户,而ASP.NET Identity就建立在这样的思想之上,使之能够简单而方便地添加第三方认证用户的支持,如微软、Google、Facebook、Twitter等。 There are some substantial benefits of using third-party authentication: Many users will already have an account, users can elect to use two-factor authentication, and you don’t have to manage user credentials in the application. In the sections that follow, I’ll show you how to set up and use third-party authentication for Google users, which Table 15-8 puts into context. 使用第三方认证有一些实际的好处:许多用户已经有了账号、用户可以选择使用双因子认证、你不必在应用程序中管理用户凭据等等。在以下小节中,我将演示如何为Google用户建立并使用第三方认证,表15-8描述了事情的情形。 Table 15-8. Putting Third-Party Authentication in Context 表15-8. 第三方认证情形 Question 问题 Answer 回答 What is it? 什么是第三方认证? Authenticating with third parties lets you take advantage of the popularity of companies such as Google and Facebook. 第三方认证使你能够利用流行公司,如Google和Facebook,的优势。 Why should I care? 为何要关心它? Users don’t like having to remember passwords for many different sites. Using a provider with large-scale adoption can make your application more appealing to users of the provider’s services. 用户不喜欢记住许多不同网站的口令。使用大范围适应的提供器可使你的应用程序更吸引有提供器服务的用户。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework. 这不是一个直接由MVC框架使用的特性。 Note The reason I have chosen to demonstrate Google authentication is that it is the only option that doesn’t require me to register my application with the authentication service. You can get details of the registration processes required at http://bit.ly/1cqLTrE. 提示:我选择演示Google认证的原因是,它是唯一不需要在其认证服务中注册我应用程序的公司。有关认证服务注册过程的细节,请参阅http://bit.ly/1cqLTrE。 15.4.1 Enabling Google Authentication 15.4.1 启用Google认证 ASP.NET Identity comes with built-in support for authenticating users through their Microsoft, Google, Facebook, and Twitter accounts as well more general support for any authentication service that supports OAuth. The first step is to add the NuGet package that includes the Google-specific additions for ASP.NET Identity. Enter the following command into the Package Manager Console: ASP.NET Identity带有通过Microsoft、Google、Facebook以及Twitter账号认证用户的内建支持,并且对于支持OAuth的认证服务具有更普遍的支持。第一个步骤是添加NuGet包,包中含有用于ASP.NET Identity的Google专用附件。请在“Package Manager Console(包管理器控制台)”中输入以下命令: Install-Package Microsoft.Owin.Security.Google -version 2.0.2 There are NuGet packages for each of the services that ASP.NET Identity supports, as described in Table 15-9. 对于ASP.NET Identity支持的每一种服务都有相应的NuGet包,如表15-9所示。 Table 15-9. The NuGet Authenticaton Packages 表15-9. NuGet认证包 Name 名称 Description 描述 Microsoft.Owin.Security.Google Authenticates users with Google accounts 用Google账号认证用户 Microsoft.Owin.Security.Facebook Authenticates users with Facebook accounts 用Facebook账号认证用户 Microsoft.Owin.Security.Twitter Authenticates users with Twitter accounts 用Twitter账号认证用户 Microsoft.Owin.Security.MicrosoftAccount Authenticates users with Microsoft accounts 用Microsoft账号认证用户 Microsoft.Owin.Security.OAuth Authenticates users against any OAuth 2.0 service 根据任一OAuth 2.0服务认证用户 Once the package is installed, I enable support for the authentication service in the OWIN startup class, which is defined in the App_Start/IdentityConfig.cs file in the example project. Listing 15-22 shows the change that I have made. 一旦安装了这个包,便可以在OWIN启动类中启用此项认证服务的支持,启动类的定义在示例项目的App_Start/IdentityConfig.cs文件中。清单15-22显示了所做的修改。 Listing 15-22. Enabling Google Authentication in the IdentityConfig.cs File 清单15-22. 在IdentityConfig.cs文件中启用Google认证 using Microsoft.AspNet.Identity;using Microsoft.Owin;using Microsoft.Owin.Security.Cookies;using Owin;using Users.Infrastructure;using Microsoft.Owin.Security.Google;namespace Users {public class IdentityConfig {public void Configuration(IAppBuilder app) {app.CreatePerOwinContext<AppIdentityDbContext>(AppIdentityDbContext.Create);app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions {AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,LoginPath = new PathString("/Account/Login"),}); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);app.UseGoogleAuthentication();} }} Each of the packages that I listed in Table 15-9 contains an extension method that enables the corresponding service. The extension method for the Google service is called UseGoogleAuthentication, and it is called on the IAppBuilder implementation that is passed to the Configuration method. 表15-9所列的每个包都含有启用相应服务的扩展方法。用于Google服务的扩展方法名称为UseGoogleAuthentication,它通过传递给Configuration方法的IAppBuilder实现进行调用。 Next I added a button to the Views/Account/Login.cshtml file, which allows users to log in via Google. You can see the change in Listing 15-23. 下一步骤是在Views/Account/Login.cshtml文件中添加一个按钮,让用户能够通过Google进行登录。所做的修改如清单15-23所示。 Listing 15-23. Adding a Google Login Button to the Login.cshtml File 清单15-23. 在Login.cshtml文件中添加Google登录按钮 @model Users.Models.LoginModel@{ ViewBag.Title = "Login";}<h2>Log In</h2> @Html.ValidationSummary()@using (Html.BeginForm()) {@Html.AntiForgeryToken();<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><div class="form-group"><label>Name</label>@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })</div><div class="form-group"><label>Password</label>@Html.PasswordFor(x => x.Password, new { @class = "form-control" })</div><button class="btn btn-primary" type="submit">Log In</button>}@using (Html.BeginForm("GoogleLogin", "Account")) {<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><button class="btn btn-primary" type="submit">Log In via Google</button>} The new button submits a form that targets the GoogleLogin action on the Account controller. You can see this method—and the other changes I made the controller—in Listing 15-24. 新按钮递交一个表单,目标是Account控制器中的GoogleLogin动作。可从清单15-24中看到该方法,以及在控制器中所做的其他修改。 Listing 15-24. Adding Support for Google Authentication to the AccountController.cs File 清单15-24. 在AccountController.cs文件中添加Google认证支持 using System.Threading.Tasks;using System.Web.Mvc;using Users.Models;using Microsoft.Owin.Security;using System.Security.Claims;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Infrastructure;using System.Web; namespace Users.Controllers {[Authorize]public class AccountController : Controller {[AllowAnonymous]public ActionResult Login(string returnUrl) {if (HttpContext.User.Identity.IsAuthenticated) {return View("Error", new string[] { "Access Denied" });}ViewBag.returnUrl = returnUrl;return View();}[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident)); AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);} [HttpPost][AllowAnonymous]public ActionResult GoogleLogin(string returnUrl) {var properties = new AuthenticationProperties {RedirectUri = Url.Action("GoogleLoginCallback",new { returnUrl = returnUrl})};HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();}[AllowAnonymous]public async Task<ActionResult> GoogleLoginCallback(string returnUrl) {ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();AppUser user = await UserManager.FindAsync(loginInfo.Login);if (user == null) {user = new AppUser {Email = loginInfo.Email,UserName = loginInfo.DefaultUserName,City = Cities.LONDON, Country = Countries.UK};IdentityResult result = await UserManager.CreateAsync(user);if (!result.Succeeded) {return View("Error", result.Errors);} else {result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);if (!result.Succeeded) {return View("Error", result.Errors);} }}ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false }, ident);return Redirect(returnUrl ?? "/");}[Authorize]public ActionResult Logout() {AuthManager.SignOut();return RedirectToAction("Index", "Home");}private IAuthenticationManager AuthManager {get {return HttpContext.GetOwinContext().Authentication;} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } The GoogleLogin method creates an instance of the AuthenticationProperties class and sets the RedirectUri property to a URL that targets the GoogleLoginCallback action in the same controller. The next part is a magic phrase that causes ASP.NET Identity to respond to an unauthorized error by redirecting the user to the Google authentication page, rather than the one defined by the application: GoogleLogin方法创建了AuthenticationProperties类的一个实例,并为RedirectUri属性设置了一个URL,其目标为同一控制器中的GoogleLoginCallback动作。下一个部分是一个神奇阶段,通过将用户重定向到Google认证页面,而不是应用程序所定义的认证页面,让ASP.NET Identity对未授权的错误进行响应: ...HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();... This means that when the user clicks the Log In via Google button, their browser is redirected to the Google authentication service and then redirected back to the GoogleLoginCallback action method once they are authenticated. 这意味着,当用户通过点击Google按钮进行登录时,浏览器被重定向到Google的认证服务,一旦在那里认证之后,便被重定向回GoogleLoginCallback动作方法。 I get details of the external login by calling the GetExternalLoginInfoAsync of the IAuthenticationManager implementation, like this: 我通过调用IAuthenticationManager实现的GetExternalLoginInfoAsync方法,我获得了外部登录的细节,如下所示: ...ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();... The ExternalLoginInfo class defines the properties shown in Table 15-10. ExternalLoginInfo类定义的属性如表15-10所示: Table 15-10. The Properties Defined by the ExternalLoginInfo Class 表15-10. ExternalLoginInfo类所定义的属性 Name 名称 Description 描述 DefaultUserName Returns the username 返回用户名 Email Returns the e-mail address 返回E-mail地址 ExternalIdentity Returns a ClaimsIdentity that identities the user 返回标识该用户的ClaimsIdentity Login Returns a UserLoginInfo that describes the external login 返回描述外部登录的UserLoginInfo I use the FindAsync method defined by the user manager class to locate the user based on the value of the ExternalLoginInfo.Login property, which returns an AppUser object if the user has been authenticated with the application before: 我使用了由用户管理器类所定义的FindAsync方法,以便根据ExternalLoginInfo.Login属性的值对用户进行定位,如果用户之前在应用程序中已经认证,该属性会返回一个AppUser对象: ...AppUser user = await UserManager.FindAsync(loginInfo.Login);... If the FindAsync method doesn’t return an AppUser object, then I know that this is the first time that this user has logged into the application, so I create a new AppUser object, populate it with values, and save it to the database. I also save details of how the user logged in so that I can find them next time: 如果FindAsync方法返回的不是AppUser对象,那么我便知道这是用户首次登录应用程序,于是便创建了一个新的AppUser对象,填充该对象的值,并将其保存到数据库。我还保存了用户如何登录的细节,以便下次能够找到他们: ...result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);... All that remains is to generate an identity the user, copy the claims provided by Google, and create an authentication cookie so that the application knows the user has been authenticated: 剩下的事情只是生成该用户的标识了,拷贝Google提供的声明(Claims),并创建一个认证Cookie,以使应用程序知道此用户已认证: ...ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);... 15.4.2 Testing Google Authentication 15.4.2 测试Google认证 There is one further change that I need to make before I can test Google authentication: I need to change the account verification I set up in Chapter 13 because it prevents accounts from being created with e-mail addresses that are not within the example.com domain. Listing 15-25 shows how I removed the verification from the AppUserManager class. 在测试Google认证之前还需要一处修改:需要修改第13章所建立的账号验证,因为它不允许example.com域之外的E-mail地址创建账号。清单15-25显示了如何在AppUserManager类中删除这种验证。 Listing 15-25. Disabling Account Validation in the AppUserManager.cs File 清单15-25. 在AppUserManager.cs文件中取消账号验证 using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Microsoft.AspNet.Identity.Owin;using Microsoft.Owin;using Users.Models; namespace Users.Infrastructure {public class AppUserManager : UserManager<AppUser> {public AppUserManager(IUserStore<AppUser> store): base(store) {}public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options,IOwinContext context) {AppIdentityDbContext db = context.Get<AppIdentityDbContext>();AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db)); manager.PasswordValidator = new CustomPasswordValidator {RequiredLength = 6,RequireNonLetterOrDigit = false,RequireDigit = false,RequireLowercase = true,RequireUppercase = true}; //manager.UserValidator = new CustomUserValidator(manager) {// AllowOnlyAlphanumericUserNames = true,// RequireUniqueEmail = true//};return manager;} }} Tip you can use validation for externally authenticated accounts, but I am just going to disable the feature for simplicity. 提示:也可以使用外部已认证账号的验证,但这里出于简化,取消了这一特性。 To test authentication, start the application, click the Log In via Google button, and provide the credentials for a valid Google account. When you have completed the authentication process, your browser will be redirected back to the application. If you navigate to the /Claims/Index URL, you will be able to see how claims from the Google system have been added to the user’s identity, as shown in Figure 15-7. 为了测试认证,启动应用程序,通过点击“Log In via Google(通过Google登录)”按钮,并提供有效的Google账号凭据。当你完成了认证过程时,浏览器将被重定向回应用程序。如果导航到/Claims/Index URL,便能够看到来自Google系统的声明(Claims),已被添加到用户的标识中了,如图15-7所示。 Figure 15-7. Claims from Google 图15-7. 来自Google的声明(Claims) 15.5 Summary 15.5 小结 In this chapter, I showed you some of the advanced features that ASP.NET Identity supports. I demonstrated the use of custom user properties and how to use database migrations to preserve data when you upgrade the schema to support them. I explained how claims work and how they can be used to create more flexible ways of authorizing users. I finished the chapter by showing you how to authenticate users via Google, which builds on the ideas behind the use of claims. 本章向你演示了ASP.NET Identity所支持的一些高级特性。演示了自定义用户属性的使用,还演示了在升级数据架构时,如何使用数据库迁移保护数据。我解释了声明(Claims)的工作机制,以及如何将它们用于创建更灵活的用户授权方式。最后演示了如何通过Google进行认证结束了本章,这是建立在使用声明(Claims)的思想基础之上的。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gz19871113/article/details/108591802。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-28 08:49:21
283
转载
转载文章
...IKI_OBJECTFILES = ${addprefix $(OBJECTDIR)/,${call oname, $(CONTIKI_SOURCEFILES)} }PROJECT_OBJECTFILES = ${addprefix $(OBJECTDIR)/,${call oname, $(PROJECT_SOURCEFILES)} } 定义CONTIKI_OBJECTFILES变量 首先用oname函数,将CONTIKI_SOURCEFILES所对应的源文件名,改为目标文件名,如process.c将会变为process.o 再在文件名前边加上前缀$(OBJECTDIR)/,前边我们知道这个变量为obj_native,故process.c会变为obj_native/process.o 这个变量应该是代表即将生成的Contiki操作系统的目标文件名 定义PROJECT_OBJECTFILES变量 功能同上 这个变量应该是代表即将生成的项目中的目标文件名 PROJECT_SOURCEFILES这个变量为空,所以PROJECT_OBJECTFILES也为空。 Provide way to create $(OBJECTDIR) if it has been removed by make clean$(OBJECTDIR):mkdir $@ $@是自动化变量,表示规则中的目标文件集。我们知道OBJECTDIR为obj_native,所以$@为obj_native。 mkdir $@生成obj_native目录。 但是这个依赖关系链,怎么会涉及到obj_native的? 调试了一下: 在生成CONTIKI_OBJECTFILES所代表的文件时,目录不存在,会先找依赖关系生成目录,再生成具体文件。 所以mkdir obj_native会被执行。 (2) ifdef APPSAPPDS = ${wildcard ${foreach DIR, $(APPDIRS), ${addprefix $(DIR)/, $(APPS)} }} \${wildcard ${addprefix $(CONTIKI)/apps/, $(APPS)} \${addprefix $(CONTIKI)/platform/$(TARGET)/apps/, $(APPS)} \$(APPS)}APPINCLUDES = ${foreach APP, $(APPS), ${wildcard ${foreach DIR, $(APPDS), $(DIR)/Makefile.$(APP)} }}-include $(APPINCLUDES)APP_SOURCES = ${foreach APP, $(APPS), $($(APP)_src)}DSC_SOURCES = ${foreach APP, $(APPS), $($(APP)_dsc)}CONTIKI_SOURCEFILES += $(APP_SOURCES) $(DSC_SOURCES)endif The project's makefile can also define in the APPS variable a list of applications from the apps/ directory that should be included in the Contiki system. hello-world这个例子没有定义APPS变量,故这段不会执行。 我们假设定义了APPS变量,其值为APPS += antelope unit-test。 相关知识点: wildcard函数: 返回所有符合pattern的文件名,以空格隔开。 $(wildcard pattern) The argument pattern is a file name pattern, typically containing wildcard characters (as in shell file name patterns). The result of wildcard is a space-separated list of the names of existing files that match the pattern. foreach函数: The syntax of the foreach function is: $(foreach var,list,text) The first two arguments, var and list, are expanded before anything else is done; note that the last argument, text, is not expanded at the same time. Then for each word of the expanded value of list, the variable named by the expanded value of var is set to that word, and text is expanded. Presumably text contains references to that variable, so its expansion will be different each time. The result is that text is expanded as many times as there are whitespace-separated words in list. The multiple expansions of text are concatenated, with spaces between them, to make the result of foreach. 每次从list中取出一个词(空格分隔),赋给var变量,然后text(一般有var变量)被拓展开来。 只要list中还有空格分隔符就会一直循环下去,每一次text返回的结果都会以空格分隔开。 ${wildcard ${foreach DIR, $(APPDIRS), ${addprefix $(DIR)/, $(APPS)} }} 先分析${foreach DIR, $(APPDIRS), ${addprefix $(DIR)/, $(APPS)} } 其中DIR是变量(var),$(APPDIRS)是列表(list),这个例子中没有定义APPDIRS这个变量,估计是用于定义除了$CONTIKI/apps/之外的apps目录。 ${addprefix $(DIR)/, $(APPS)}是text。我们假设定义了APPDIRS为a b。 那么第一次:DIR 会被赋值为a,${addprefix $(DIR)/, $(APPS)},又我们假定APPS为antelope unit-test,所以最终会被拓展为a/antelope a/unit-test。 DIR 会被赋值为b,${addprefix $(DIR)/, $(APPS)},又我们假定APPS为antelope unit-test,所以最终会被拓展为b/antelope b/unit-test。 最终这两次结果会以空格分隔开,即a/antelope a/unit-test b/antelope b/unit-test ${wildcard a/antelope a/unit-test b/antelope b/unit-test} 返回空,因为找不到符合这样的目录。 所以最终这句语句,实现的功能是,返回$APPDIRS目录中,所有符合$APPS的目录。 ${wildcard ${addprefix $(CONTIKI)/apps/, $(APPS)} 这句语句返回$(CONTIKI)/apps/目录下所有符合$APPS的目录,即contiki-release-2-7/apps/antelope contiki-release-2-7/apps/unit-test ${addprefix $(CONTIKI)/platform/$(TARGET)/apps/, $(APPS)} 这句语句返回$(CONTIKI)/platform/$(TARGET)/apps/目录下所有$APPS的目录,即contiki-release-2-7/platform/native/apps/antelope contiki-release-2-7/platform/native/apps/unit-test。 在contiki-release-2-7/platform/native目录下,并没有apps目录,后边有差错处理机制。 $(APPS) 在当前目录下的所有$APPS目录,即antelope unit-test。 在hello-world例子中,并没有这些目录。 所以APPDS变量是包含所有与$APPS有关的目录。 APPINCLUDES变量是所有需要导入的APP Makefile文件。 在所有APPDS目录下,所有Makefile.$(APPS)文件。 在我们的假设条件APPS = antelope unit-test, APPDIRS = 只会导入contiki-release-2-7/apps/antelope/Makefile.antelope contiki-release-2-7/apps/unit-test/Makefile.unit-test 其余的均不存在,所以在include指令前要有符号-,即出错继续执行后续指令。 contiki-release-2-7/apps/antelope/Makefile.antelope: 分别定义了两个变量,antelope_src用于保存antelope这个app的src文件,antelope_dsc用于保存antelope这个app的dsc文件。 contiki-release-2-7/apps/unit-test/Makefile.unit-test: 分别定义了两个变量,unit-test_src用于保存unit-test这个app的src文件,unit-tes_dsc用于保存unit-test这个app的dsc文件。 变量APP_SOURCES APP_SOURCES = ${foreach APP, $(APPS), $($(APP)_src)} 取出所有APPS中的src文件变量,这个例子是$(antelope_src) 和$(unit-test_src) 变量APP_SOURCES DSC_SOURCES = ${foreach APP, $(APPS), $($(APP)_dsc)} 取出所有APPS中的dsc文件变量,这个例子是$(antelope_dsc) 和$(unit-test_dsc) CONTIKI_SOURCEFILES += $(APP_SOURCES) $(DSC_SOURCES) 这段话的最终目的: 将$APPS相关的所有源文件添加进CONTIKI_SOURCEFILES变量中。 (3) target_makefile := $(wildcard $(CONTIKI)/platform/$(TARGET)/Makefile.$(TARGET) ${foreach TDIR, $(TARGETDIRS), $(TDIR)/$(TARGET)/Makefile.$(TARGET)}) Check if the target makefile exists, and create the object directory if necessary.ifeq ($(strip $(target_makefile)),)${error The target platform "$(TARGET)" does not exist (maybe it was misspelled?)}elseifneq (1, ${words $(target_makefile)})${error More than one TARGET Makefile found: $(target_makefile)}endifinclude $(target_makefile)endif 这断代码主要做的就是,找到在所有TAGET目录下找到符合的Makefile.$(TARGET)文件,放到target_makefile变量中。 再检查是否存在或者重复。并做相应的错误提示信息。 ${error The target platform "$(TARGET)" does not exist (maybe it was misspelled?)} ${error More than one TARGET Makefile found: $(target_makefile)} 我们这个例子中 TARGET = native 并且 TARGETDIRS为空 所以最后会导入$(CONTIKI)/platform/native/Makefile.native 接下去要开始分析target和cpu的makefile文件了。 转载于:https://www.cnblogs.com/songdechiu/p/6012718.html 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_34399060/article/details/94095820。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-03-28 09:49:23
282
转载
MySQL
...易处理场景,但在结合Hadoop、Spark等大数据框架后,也能够实现大规模数据分析和处理。比如使用Apache Sqoop工具将MySQL数据导入HDFS,或通过JDBC连接Spark SQL对MySQL数据进行复杂分析。 此外,对于系统安全性的考虑,如何有效防止SQL注入、实施权限管理以及加密敏感数据也是MySQL使用者需要关注的重点。MySQL自带的多层访问控制机制及密码加密策略可确保数据安全性,同时,业界还推荐遵循OWASP SQL注入防护指南来编写安全的SQL查询语句。 总之,在实际工作中,熟练掌握MySQL并结合最新的技术趋势与最佳实践,将有助于构建更为稳定、高效且安全的系统数据存储解决方案。
2023-01-17 16:44:32
123
程序媛
Flink
...allel and Distributed Systems》的研究论文提出了一种基于机器学习的预测模型,可以在网络分区发生前进行预警,从而提前采取预防措施。该模型通过分析历史数据,识别出可能导致网络分区的因素,并据此优化系统的配置和资源分配。 这些研究不仅提高了我们对网络分区问题的理解,也为未来的设计和开发提供了宝贵的参考。面对日益复杂的分布式系统环境,如何有效应对网络分区带来的挑战,将是未来一段时间内技术发展的关键方向之一。
2024-12-30 15:34:27
45
飞鸟与鱼
Mahout
...allel and Distributed Systems》上的研究指出,利用智能调度算法,可以根据实时负载情况动态调整作业优先级,从而提高系统的整体吞吐量。此外,有专家建议,在实际应用中,应根据具体业务场景灵活调整Mahout的各项配置参数,以达到最优效果。 总之,Mahout作为一种成熟的开源工具,在大数据处理领域展现出巨大的潜力。通过不断优化其内部机制,可以使其在更多场景下发挥重要作用,帮助企业更好地理解和利用海量数据。未来,随着技术的进步,我们期待看到更多创新性的解决方案出现,进一步推动大数据技术的发展。
2025-03-03 15:37:45
65
青春印记
Hive
...演着关键角色,它作为Hadoop生态系统的一部分,使得非技术人员也能通过SQL查询访问Hadoop集群中的海量数据。你知道吗,头一回试着用Hive JDBC搭桥的时候,可能会遇到一个超级烦人的问题:就像在茫茫大海里找钥匙一样,就是找不到那个该死的JDBC驱动或者Hive的client jar包,真是让人抓狂!接下来,咱们一起踏上探索之旅,我保证会给你细细讲解这个难题,还贴心地送上实用的解决妙招,让你的Hive冒险路途畅通无阻,轻松愉快! 二、背景与理解 1. Hive概述 Hive是一种基于Hadoop的数据仓库工具,它允许用户以SQL的方式查询存储在HDFS上的数据。你知道的,想要用JDBC跟Hive来个友好交流,第一步得确认那个Hive服务器已经在那儿转悠了,而且JDBC的桥梁和必要的jar文件都得像好朋友一样好好准备齐全。 2. JDBC驱动的重要性 JDBC(Java Database Connectivity)是Java语言与数据库交互的接口,驱动程序则是这个接口的具体实现。就像试图跟空房子聊天一样,没对的“钥匙”(驱动),就感觉像是在大海捞针,怎么也找不到那个能接通的“门铃号码”(正确驱动)。 三、常见问题及解决方案 1. 缺失的JDBC驱动 - 检查环境变量:确保JAVA_HOME和HIVE_HOME环境变量设置正确,因为Hive JDBC驱动通常位于$HIVE_HOME/lib目录下的hive-jdbc-.jar文件。 - 手动添加驱动:如果你在IDE中运行,可能需要在项目构建路径中手动添加驱动jar。例如,在Maven项目中,可以在pom.xml文件中添加如下依赖: xml org.apache.hive hive-jdbc 版本号 - 下载并放置:如果在服务器上运行,可能需要从Apache Hive的官方网站下载对应版本的驱动并放入服务器的类路径中。 2. Hive Client jar包 - 确认包含Hive Server的jar:Hive Server通常包含了Hive Client的jar,如果单独部署,确保$HIVE_SERVER2_HOME/lib目录下存在hive-exec-.jar等Hive相关jar。 3. Hive Server配置 - Hive-site.xml:检查Hive的配置文件,确保标签内的javax.jdo.option.ConnectionURL和标签内的javax.jdo.option.ConnectionDriverName指向正确的JDBC URL和驱动。 四、代码示例与实战演练 1. 连接Hive示例(Java) java try { Class.forName("org.apache.hive.jdbc.HiveDriver"); Connection conn = DriverManager.getConnection( "jdbc:hive2://localhost:10000/default", "username", "password"); Statement stmt = conn.createStatement(); String sql = "SELECT FROM my_table"; ResultSet rs = stmt.executeQuery(sql); // 处理查询结果... } catch (Exception e) { e.printStackTrace(); } 2. 错误处理与诊断 如果上述代码执行时出现异常,可能是驱动加载失败或者URL格式错误。查看ClassNotFoundException或SQLException堆栈信息,有助于定位问题。 五、总结与经验分享 面对这类问题,耐心和细致的排查至关重要。记住,Hive的世界并非总是那么直观,尤其是当涉及到多个组件的集成时。逐步检查环境配置、依赖关系以及日志信息,往往能帮助你找到问题的根源。嘿,你知道吗,学习Hive JDBC就像解锁新玩具,开始可能有点懵,但只要你保持那股子好奇劲儿,多动手试一试,翻翻说明书,一点一点地,你就会上手得越来越溜了。关键就是那份坚持和探索的乐趣,时间会带你熟悉这个小家伙的每一个秘密。 希望这篇文章能帮你解决在使用Hive JDBC时遇到的困扰,如果你在实际操作中还有其他疑问,别忘了社区和网络资源是解决问题的好帮手。祝你在Hadoop和Hive的探索之旅中一帆风顺!
2024-04-04 10:40:57
769
百转千回
Apache Pig
...ache Pig作为Hadoop生态系统中的一员,以其简洁的脚本语言和强大的数据处理能力,成为众多数据工程师和分析师的首选工具。今天,我们将聚焦于Apache Pig的核心组件之一——Scripting Shell,探索它如何简化复杂的数据处理任务,并提供实际操作的示例。 二、Apache Pig简介 从概念到应用 Apache Pig是一个基于Hadoop的大规模数据处理系统,它提供了Pig Latin语言,一种高级的、易读易写的脚本语言,用于描述数据流和转换逻辑。Pig的主要优势在于其抽象层次高,可以将复杂的查询逻辑转化为简单易懂的脚本形式,从而降低数据处理的门槛。 三、Scripting Shell的引入 让Pig脚本更加灵活 Apache Pig提供了多种运行环境,其中Scripting Shell是用户最常使用的交互式环境之一。哎呀,小伙伴们!使用Scripting Shell,咱们可以直接在命令行里跑Pig脚本啦!这不就方便多了嘛,想看啥结果立马就能瞅到,遇到小问题还能马上调试调调试,改一改,试一试,挺好玩的!这样子,咱们的操作过程就像在跟老朋友聊天一样,轻松又自在~哎呀,这种交互方式简直是开发者的大救星啊!特别是对新手来说,简直就像有了个私人教练,手把手教你Pig的基本语法规则和工作流程,让你的学习之路变得轻松又愉快。就像是在玩游戏一样,不知不觉中就掌握了技巧,感觉真是太棒了! 四、使用Scripting Shell进行数据处理 实战演练 让我们通过几个具体的例子来深入了解如何利用Scripting Shell进行数据处理: 示例1:加载并查看数据 首先,我们需要从HDFS加载数据集。假设我们有一个名为orders.txt的文件,存储了订单信息,我们可以使用以下脚本来加载数据并查看前几行: pig A = LOAD 'hdfs://path_to_your_file/orders.txt' USING PigStorage(',') AS (order_id:int, customer_id:int, product_id:int, quantity:int); dump A; 在这个例子中,我们使用了LOAD语句从HDFS加载数据,PigStorage(',')表示数据分隔符为逗号,然后定义了一个元组类型(order_id:int, customer_id:int, product_id:int, quantity:int)。dump命令则用于输出数据集的前几行,帮助我们验证数据是否正确加载。 示例2:数据过滤与聚合 接下来,假设我们想要找出每个客户的总订单数量: pig B = FOREACH A GENERATE customer_id, SUM(quantity) as total_quantity; C = GROUP B by 0; D = FOREACH C GENERATE key, SUM(total_quantity); dump D; 在这段脚本中,我们首先对原始数据集A进行处理,计算每个客户对应的总订单数量(步骤B),然后按照客户ID进行分组(步骤C),最后再次计算每组的总和(步骤D)。最终,dump D命令输出结果,显示了每个客户的ID及其总订单数量。 示例3:数据清洗与异常值处理 在处理真实世界的数据时,数据清洗是必不可少的步骤。例如,假设我们发现数据集中存在无效的订单ID: pig E = FILTER A BY order_id > 0; dump E; 通过FILTER语句,我们仅保留了order_id大于0的记录,这有助于排除无效数据,确保后续分析的准确性。 五、结语 Apache Pig的未来与挑战 随着大数据技术的不断发展,Apache Pig作为其生态中的重要组成部分,持续进化以适应新的需求。哎呀,你知道吗?Scripting Shell这个家伙,简直是咱们数据科学家们的超级帮手啊!它就像个神奇的魔法师,轻轻一挥,就把复杂的数据处理工作变得简单明了,就像是给一堆乱糟糟的线理了个顺溜。而且,它还能搭建起一座桥梁,让咱们这些数据科学家们能够更好地分享知识、交流心得,就像是在一场热闹的聚会里,大家围坐一起,畅所欲言,气氛超棒的!哎呀,你知道不?现在数据越来越多,越来越复杂,咱们得好好处理才行。那啥,Apache Pig这东西,以后要想做得更好,得解决几个大问题。首先,怎么让性能更上一层楼?其次,怎么让系统能轻松应对更多的数据?最后,怎么让用户用起来更顺手?这些可是Apache Pig未来的头等大事! 通过本文的探索,我们不仅了解了Apache Pig的基本原理和Scripting Shell的功能,还通过实际示例亲身体验了如何使用它来进行高效的数据处理。希望这些知识能够帮助你开启在大数据领域的新篇章,探索更多可能!
2024-09-30 16:03:59
95
繁华落尽
Hive
Hive无法访问HDFS文件系统的问题排查与解决 一、引言 Hive与HDFS的亲密关系 大家好啊!今天咱们聊聊Hive和HDFS这对CP(组合)。Hive 这个东西呢,其实就是个搭在 Hadoop 身上的数据仓库工具,说白了嘛,它的工作方式特别直白——把你的 SQL 查询语句给翻译成 MapReduce 任务,然后甩给 Hadoop 去干活儿。而HDFS呢,就是存储这些数据的地方。它们就像一对老朋友,互相依赖,缺一不可。 但有时候,这俩家伙可能会闹别扭,尤其是当你发现Hive突然不能访问HDFS了。这可真是让人头疼,因为这意味着你的数据查询直接凉凉。所以今天我们就来聊聊,为什么会出现这种情况,以及该怎么解决。 二、可能的原因 为什么Hive访问不了HDFS? 2.1 网络问题 首先,我们得想想是不是网络出了问题。嘿,你知道吗?我猜你们公司那位网络大神最近是不是偷偷调整了防火墙的设置?或者是服务器那边抽风了,直接断网了?反正不管咋回事儿,现在Hive跟HDFS就像是隔了一座大山,怎么也连不上,所以它想读数据都读不到啊! 举个例子吧,假设你的Hive配置文件里写着HDFS的地址是hdfs://namenode:9000/,但是实际上NameNode所在的机器根本不在网络范围内,那Hive当然会报错啦。 解决方法:检查一下网络连接是否正常。你可以试着ping一下HDFS的NameNode地址,看看能不能通。如果不行的话,赶紧找网络管理员帮忙修一下。 2.2 权限问题 其次,权限问题也是常见的原因。HDFS对文件和目录是有严格权限控制的,如果你的用户没有足够的权限去读取某个文件,那么Hive自然也无能为力。 举个栗子,假如你有一个HDFS路径/user/hive/warehouse/my_table,但是这个目录的权限设置成了只有root用户才能访问,而你的Hive用户不是root,那肯定就悲剧了。 解决方法:检查HDFS上的文件和目录权限。如果你想看看某个文件的权限,可以用这个命令:hadoop fs -ls /path/to/file。看完之后,要是觉得权限不对劲,就动手改一下呗,比如说用hadoop fs -chmod 755 /path/to/file,给它整成合适的权限就行啦! 2.3 HDFS服务未运行 还有一种可能是HDFS服务本身挂掉了。比如说,NameNode突然罢工了,DataNode也闹起了情绪,甚至整个集群都瘫痪了,啥都不干了。哎呀糟糕了,这情况有点悬啊!HDFS直接罢工了,完全不干活,任凭Hive使出浑身解数也无济于事。这下可好,整个系统像是瘫了一样,啥也跑不起来了。 解决方法:检查HDFS的服务状态。可以通过命令jps查看是否有NameNode和DataNode进程在运行。如果没有,那就得赶紧启动它们,或者重启整个HDFS服务。 三、实战演练 Hive访问HDFS的具体操作 接下来,我们通过一些实际的例子来看看如何用Hive操作HDFS。 3.1 创建表并加载数据到HDFS 假设我们现在要创建一个简单的表,并将数据加载到HDFS中。我们可以先创建一个本地文件data.txt,内容如下: id,name,age 1,Alice,25 2,Bob,30 3,Charlie,35 然后上传到HDFS: bash hadoop fs -put data.txt /user/hive/warehouse/my_table/ 接着在Hive中创建表: sql CREATE TABLE my_table ( id INT, name STRING, age INT ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE; 最后加载数据: sql LOAD DATA INPATH '/user/hive/warehouse/my_table/data.txt' INTO TABLE my_table; 这样,我们的数据就成功存到了HDFS上,并且Hive也能读取到了。 3.2 查询数据 现在我们可以试试查询数据: sql SELECT FROM my_table; 如果一切正常,你应该能看到类似这样的结果: OK 1 Alice 25 2 Bob 30 3 Charlie 35 Time taken: 0.077 seconds, Fetched: 3 row(s) 但如果之前出现了访问不了HDFS的情况,这里就会报错。所以我们要确保每一步都正确无误。 四、总结与展望 总之,Hive无法访问HDFS的问题虽然看起来很复杂,但实际上只要找到根本原因,解决起来并不难。无论是网络问题、权限问题还是服务问题,都有相应的解决办法。嘿,大家听我说啊!以后要是再碰到这种事儿,别害怕,也别乱了阵脚。就当是玩个解谜游戏,一步一步慢慢来,肯定能找出办法搞定它! 未来,随着大数据技术的发展,Hive和HDFS的功能也会越来越强大。说不定哪天它们还能像人类一样交流感情呢!(开玩笑啦) 好了,今天的分享就到这里啦。如果你还有什么疑问或者经验想要分享,欢迎随时留言讨论哦!让我们一起进步,一起探索大数据的奥秘吧!
2025-04-01 16:11:37
105
幽谷听泉
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
printf "%-10s %-10s\n" "Name" "Age"
- 打印格式化字符串,用于创建表格布局。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"