前端技术
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
[Java接口实现Transform插件数...]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Datax
一、引言 在大数据时代,数据的清洗和过滤是非常重要的一个环节。而Datax作为一个强大的数据传输工具,不仅可以用来进行数据同步,也可以用于数据过滤处理。本篇文章将带大家了解如何在Datax中实现数据的过滤处理。 二、基本概念介绍 首先,我们需要明确什么是数据过滤。数据过滤是指根据某些特定条件对数据进行筛选,保留符合条件的数据,删除不符合条件的数据的过程。在Datax中,我们可以使用IF判断语句来实现数据过滤。 三、IF判断语句的基本语法 在Datax中,IF判断语句的基本语法如下: IF [condition] THEN [true part] ELSE [false part] 其中,[condition]是我们要判断的条件,[true part]是当条件为真时执行的操作,[false part]是当条件为假时执行的操作。 四、实例分析 下面我们就通过一个具体的实例来学习如何在Datax中实现数据的过滤处理。 假设我们有一个订单表,包含字段id, name, amount, status等,我们想要找出所有状态为"已完成"的订单。 1. 首先,我们在配置文件中添加以下内容 2. 在上述配置文件中,我们首先定义了一个源通道(in_channel)和目标通道(out_channel)。源通道通过SQL查询获取所有的订单,然后目标通道通过IF判断语句筛选出状态为"已完成"的订单,并将其插入到新的表filtered_orders中。 五、总结 以上就是在Datax中实现数据过滤处理的一个简单例子。瞧瞧这个例子,咱们就能明白,在Datax这玩意儿里头,咱能够超级轻松地用IF判断语句给数据做个筛选处理,简直不要太方便!如果你也想在你的项目中实现数据过滤处理,不妨试试看Datax吧!
2023-01-03 10:03:02
435
灵动之光-t
Java
...问和修改同一代码块或数据时,如果能确保在任何情况下,结果都是正确的且符合预期,那么称这段代码或者数据结构是线程安全的。在Java中,通过synchronized关键字可以实现对共享资源的互斥访问,从而达到线程安全的目的。 Future模式 , Future模式是Java并发编程中的一个设计模式,它提供了一种异步编程机制,允许主线程提交任务后继续执行其他操作,而非等待该任务完成。通过调用ExecutorService的submit()方法提交一个Callable任务,系统会返回一个Future对象,这个对象代表了该异步计算的结果。主线程可以在任何时候通过调用Future.get()方法来获取计算结果,如果结果尚未准备好,该方法将会阻塞直到结果可用。 Callback模式(回调函数) , Callback模式是一种设计模式,常用于异步编程场景中处理异步操作的结果。在这种模式下,一个对象(通常是客户端)注册一个方法给另一个对象(服务端),当服务端完成特定的操作或事件发生时,会调用预先注册的方法(即回调函数)通知客户端,并将相关结果作为参数传递。在Java中,可以通过接口实现回调逻辑,使得异步任务完成后能够以非阻塞的方式通知并处理结果。例如,在网络请求、I/O操作等场景中广泛应用回调模式进行异步处理。
2023-05-04 14:50:34
409
码农
ZooKeeper
...分布式系统的世界里,数据同步和消息传递是常见的需求。而在这其中,有一种模型——数据发布订阅模型。说白了,就是一旦我们有了新鲜出炉的数据,就会用一种特定的方式告诉所有关注的朋友们。这样一来,他们就能立马去把自己的状态更新一下啦!那么,在ZooKeeper这个强大的分布式协调服务中,我们如何实现这种模型呢? 二、什么是ZooKeeper? ZooKeeper是一个分布式的,开放源码的服务,用于配置维护、命名注册、分布式同步等。它是一个为分布式应用提供一致性服务的软件。 三、ZooKeeper的数据发布订阅模型 在ZooKeeper中,我们可以使用"事件监听器"来实现数据发布订阅模型。当节点发生变化时,ZooKeeper就会触发一个事件,我们的监听器就可以接收到这个事件,并进行相应的处理。 四、实例代码演示 首先,我们需要创建一个ZooKeeper客户端: java ZooKeeper zk = new ZooKeeper("localhost:2181", 5000, null); 然后,我们需要定义一个事件监听器: java public class MyWatcher implements Watcher { @Override public void process(WatchedEvent event) { System.out.println("Received event: " + event); } } 接下来,我们需要将这个监听器添加到ZooKeeper客户端上: java zk.addAuthInfo("digest", "username:password".getBytes()); zk.exists("/path/to/your/node", false, new MyWatcher()); 在这个例子中,我们监听了"/path/to/your/node"节点的变化。当这个节点有了新动静,ZooKeeper就会像贴心的小秘书一样,立马发出一个通知事件。而我们的监听器呢,就像时刻准备着的收音机,能够稳稳接收到这个消息提醒。 五、结论 总的来说,ZooKeeper提供了非常方便的方式来实现数据发布订阅模型。当你把事件监听器设定好,然后把它挂载到ZooKeeper客户端上,就仿佛给你的数据同步和消息传递装上了顺风耳和飞毛腿,这样一来,无论是实时的数据更新还是信息传输都能轻松搞定了。这就是我在ZooKeeper中的数据发布订阅模型的理解,希望对你有所帮助。 六、总结 通过这篇文章,你是否对ZooKeeper有了更深的理解?无论你是开发者还是研究者,我都希望你能利用ZooKeeper的强大功能,解决你的问题,推动你的项目向前发展。记住了啊,ZooKeeper可不只是个工具那么简单,它更代表着一种思考方式,一种应对问题的独特招数。所以,让我们一起探索更多的可能性,一起创造更美好的未来吧!
2023-10-24 09:38:57
71
星河万里-t
Hibernate
...bernate,这个Java ORM框架,就像是一位魔术师,让我们在Java后端的世界里能够轻松地与数据库进行交互。你知道吗,这家伙还有个不显眼的绝招,那就是能呼唤出存储过程,这简直就是给我们的编程工作开了个超方便的小灶,让效率和灵活性嗖嗖地上升!嘿伙计们,今天咱们就来聊聊怎么在Hibernate这个大家伙里顺溜地玩转存储过程,让代码既高效又酷炫! 二、什么是存储过程 存储过程是预先编写并保存在数据库中的SQL语句集合,它们可以接受参数,执行复杂的逻辑,并返回结果。你知道吗,存储过程就像是个超级小巧的魔术盒,它能把数据压缩得嗖嗖的,这样咱们的网络传输就能快上好几倍,而且还能让那些复杂的业务规则保持得井井有条,就像拆箱游戏一样,每个步骤都清晰明了。 三、在Hibernate中调用存储过程 1. 创建存储过程 在MySQL中,一个简单的存储过程示例如下: sql CREATE PROCEDURE sp_GetUsers (IN username VARCHAR(50)) BEGIN SELECT FROM users WHERE username = ?; END; 2. 使用Hibernate调用存储过程 在Hibernate中,我们需要通过Query接口或者Session对象来执行存储过程。下面是一个简单的例子: java @Autowired private SessionFactory sessionFactory; public List getUsers(String username) { String hql = "CALL sp_GetUsers(:username)"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setParameter("username", username); return query.list(); } 四、存储过程的优势与应用场景 1. 性能优化 存储过程在数据库内部执行,避免了每次查询时的序列化和反序列化,提高了效率。 2. 安全性 存储过程可以控制对数据库的访问权限,保护敏感数据。 3. 业务逻辑封装 对于复杂的业务操作,如审计、报表生成等,存储过程是很好的解决方案。 五、存储过程的注意事项 1. 避免过度使用 虽然存储过程有其优势,但过多的数据库操作可能会导致代码耦合度增加,维护困难。 2. 参数类型映射 确保传递给存储过程的参数类型与定义的参数类型一致,否则可能导致异常。 六、总结与展望 Hibernate的存储过程功能为我们提供了强大的数据库操作手段,使得我们在处理复杂业务逻辑时更加得心应手。然而,就像任何工具一样,合理使用才是关键。一旦摸透了存储过程的门道,嘿,那用Hibernate这家伙就能如虎添翼啦!不仅能让你的应用跑得飞快,还能让代码维护起来轻松愉快,就像是给车加满了油,顺畅无比。 最后,记住,编程就像烹饪,选择合适的工具和方法,才能做出美味的菜肴。Hibernate就像那个神奇的调味料,给我们的编程世界增添了不少色彩和活力,让代码不再单调乏味。
2024-04-30 11:22:57
520
心灵驿站
MyBatis
...yBatis批量插入数据,MyBatis拦截器为何失效? 在Java开发的世界里,MyBatis作为一款优秀的持久层框架,因其强大的灵活性和易用性而备受开发者喜爱。在实际动手操作的时候,我们免不了会遇到一些“始料未及”的小插曲。比如,当你兴冲冲地用MyBatis做批量插入时,却发现那个自定义的拦截器好像闹罢工了,压根没起到应有的效果。本文将带你深入探讨这个问题,并通过实例代码来剖析其背后的原理及解决方案。 1. MyBatis拦截器简介 首先,我们回顾一下MyBatis拦截器的概念。在MyBatis这个工具里,拦截器就像是个灵活的小帮手,它玩的是一种全局策略设计模式的把戏。简单来说,就是在执行SQL映射语句这个关键步骤前后,咱们可以借助拦截器随心所欲地添加一些额外操作,让整个过程更加个性化和丰富化。例如,我们可以利用拦截器实现日志记录、权限验证、事务控制等功能。 java @Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})}) public class MyInterceptor implements Interceptor { // 拦截方法的具体实现... } 2. 批量插入数据与拦截器失效之谜 通常情况下,当我们进行单条数据插入时,自定义的拦截器工作正常,但当切换到批量插入时(如标签中的foreach循环),拦截器似乎就失去了作用。这是为什么呢? 让我们先来看一个简单的批量插入示例: xml INSERT INTO table_name (column1, column2) VALUES ({item.column1}, {item.column2}) 以及对应的Java调用: java List itemList = ...; // 需要插入的数据列表 sqlSession.insert("batchInsert", itemList); 此时,如果你的拦截器是用来监听Executor.update()方法的,那么在批量插入场景下,MyBatis会优化执行过程,以减少数据库交互次数,直接一次性执行包含多组值的INSERT SQL语句,而非多次调用update()方法,这就导致了拦截器可能只在批处理的开始和结束时各触发一次,而不是对每一条数据插入都触发。 3. 解析与思考 所以,这不是拦截器本身的失效,而是由于MyBatis内部对批量操作的优化处理机制所致。在处理批量操作时,MyBatis可不把它当成一连串独立的SQL执行任务,而是视为一个整体的大更新动作。所以呢,我们在设计拦截器的时候,得把这个特殊情况给考虑进去。 4. 解决方案与应对策略 针对上述情况,我们可以采取以下策略: - 修改拦截器逻辑:调整拦截器的实现方式,使其能够适应批量操作的特性。例如,可以在拦截器中检查SQL语句是否为批量插入,如果是,则获取待插入的所有数据,遍历并逐个执行拦截逻辑。 - 利用插件API:MyBatis提供了一些插件API,比如ParameterHandler,可以用来获取参数对象,进而解析出批量插入的数据,再在每个数据项上执行拦截逻辑。 java @Override public Object intercept(Invocation invocation) throws Throwable { if (isBatchInsert(invocation)) { Object parameter = invocation.getArgs()[1]; // 对于批量插入的情况,解析并处理parameter中的每一条数据 for (Item item : (List) parameter) { // 在这里执行你的拦截逻辑 } } return invocation.proceed(); } private boolean isBatchInsert(Invocation invocation) { MappedStatement ms = (MappedStatement) invocation.getArgs()[0]; return ms.getId().endsWith("_batchInsert"); } 总之,理解MyBatis的工作原理以及批量插入的特点,有助于我们更好地调试和解决这类看似“拦截器失效”的问题。通过巧妙地耍弄和微调拦截器的逻辑设置,我们能够确保无论遇到多么复杂的场景,拦截器都能妥妥地发挥它的本职功能,真正做到“兵来将挡,水来土掩”。
2023-07-24 09:13:34
113
月下独酌_
Scala
...这就是所谓的“只关注实现的接口或满足的条件”,而不是纠结于它的具体身份。 想象一下,你是一个动物园管理员,你知道每种动物都有一个eat的行为,但并不需要确切知道它们是狮子、老虎还是熊猫。在Scala的世界里,这就对应于存在类型的概念。 scala trait Eater { def eat(food: String): Unit } val animal: Eater forSome { type T } = new Animal() { def eat(food: String) = println(s"Animal is eating $food") } 上述代码中,Eater forSome { type T }就是一个存在类型,我们只知道animal实现了Eater特质,而无需关心其具体的类型信息。 2. 存在类型的语法与理解 在Scala中,存在类型的语法形式通常表现为Type forSome { TypeBounds }。这里的TypeBounds是对未知类型的一种约束或定义,可以是特质、类或其他类型参数。 例如: scala val list: List[T] forSome { type T <: AnyRef } = List("Apple", "Banana") list.foreach(println) 在这个例子中,我们声明了一个列表list,它的元素类型T满足AnyRef(所有引用类型的超类)的下界约束,但我们并不知道T具体是什么类型,只知道它可以安全地传递给println函数。 3. 存在类型的实用场景 存在类型在实际编程中主要用于泛型容器的返回和匿名类型表达。特别是在捣鼓API设计的时候,当你想把那些复杂的实现细节藏起来,只亮出真正需要的接口给大伙儿用,这时候类型的作用就凸显出来了,简直不能更实用了。 例如,假设我们有一个工厂方法,它根据配置创建并返回不同类型的数据库连接: scala trait DatabaseConnection { def connect(): Unit def disconnect(): Unit } def createDatabaseConnection(config: Config): DatabaseConnection forSome { type T <: DatabaseConnection } = { // 根据config创建并返回一个具体的DatabaseConnection实现 // ... val connection: T = ... // 假设这里已经创建了某个具体类型的数据库连接 connection } val connection = createDatabaseConnection(myConfig) connection.connect() connection.disconnect() 在这里,使用者只需要知道createDatabaseConnection返回的是某种实现了DatabaseConnection接口的对象,而不必关心具体的实现类。 4. 对存在类型的思考与探讨 存在类型虽然强大,但使用时也需要谨慎。要是老这么使劲儿用,可能会把一些类型信息给整没了,这样一来,编译器就像个近视眼没戴眼镜,查不出代码里所有的类型毛病。这下可好,代码不仅读起来费劲多了,安全性也大打折扣,就像你走在满是坑洼的路上,一不小心就可能摔跟头。同时,对于过于复杂的类型系统,理解和调试也可能变得困难。 总的来说,Scala的存在类型就像是编程世界里的“薛定谔的猫”,它的具体类型取决于运行时的状态,这为我们提供了更加灵活的设计空间,但同时也要求我们具备更深厚的类型系统理解和良好的抽象思维能力。所以在实际动手开发的时候,咱们得看情况灵活应变,像聪明的狐狸一样权衡这个高级特性的优缺点,找准时机恰到好处地用起来。
2023-09-17 14:00:55
42
梦幻星空
Hadoop
JDBC , Java Database Connectivity,Java数据库连接。在文中,JDBC是一种用于执行SQL语句并与关系型数据库进行交互的Java API规范。Sqoop利用JDBC接口与MySQL、Oracle等数据库建立连接,实现对数据库中数据的读取和操作。 Hadoop分布式文件系统(HDFS) , 一种为大规模数据存储而设计的分布式文件系统,是Apache Hadoop项目的核心组件之一。在Sqoop的工作机制中,它将从关系型数据库抽取的数据转换并加载到HDFS上,以供Hadoop生态系统中的其他组件如MapReduce或Spark进行大数据处理和分析。 MapReduce , 一种编程模型和相关实现,用于处理海量数据集的并行运算。在Sqoop的应用场景中,虽然并未直接提到MapReduce,但Sqoop导出的数据通常会进一步通过MapReduce作业进行分布式计算和分析。MapReduce通过“Map(映射)”阶段将大任务分解成多个小任务,并行执行;然后通过“Reduce(规约)”阶段汇总各个小任务的结果,最终完成大规模数据处理任务。 Hive , 一个基于Hadoop的数据仓库工具,可以将结构化的数据文件映射为一张数据库表,并提供SQL查询功能。在Sqoop应用场景中,用户可以使用Sqoop将业务数据同步到Hive中,从而借助Hive的SQL接口实现更方便的数据查询和分析,构建用户画像或其他大数据应用。
2023-12-23 16:02:57
264
秋水共长天一色-t
SeaTunnel
...Tunnel处理流式数据并确保ExactlyOnce语义? 在大数据领域,实时流式数据的处理与保证数据处理的 ExactlyOnce 语义一直是技术挑战的核心。SeaTunnel(原名Waterdrop),作为一款开源、高性能、易扩展的数据集成平台,能够高效地处理流式数据,并通过其特有的设计和功能实现 ExactlyOnce 的数据处理保证。本文将深入探讨如何利用SeaTunnel处理流式数据,并通过实例展示如何确保 ExactlyOnce 语义。 1. SeaTunnel 简介 SeaTunnel 是一个用于海量数据同步、转换和计算的统一平台,支持批处理和流处理模式。它拥有一个超级热闹的插件生态圈,就像一个万能的桥梁,能够轻松连接各种数据源和目的地,比如 Kafka、MySQL、HDFS 等等,完全不需要担心兼容性问题。而且,对于 Flink、Spark 这些计算引擎大佬们,它也能提供超棒的支持和服务,让大家用起来得心应手,毫无压力。 2. 使用SeaTunnel处理流式数据 2.1 流式数据源接入 首先,我们来看如何使用SeaTunnel从Kafka获取流式数据。以下是一个配置示例: yaml source: type: kafka09 bootstrapServers: "localhost:9092" topic: "your-topic" groupId: "sea_tunnel_group" 上述代码片段定义了一个Kafka数据源,SeaTunnel会以消费者的身份订阅指定主题并持续读取流式数据。 2.2 数据处理与转换 SeaTunnel支持多种数据转换操作,例如清洗、过滤、聚合等。以下是一个简单的字段筛选和转换示例: yaml transform: - type: select fields: ["field1", "field2"] - type: expression script: "field3 = field1 + field2" 这段配置表示仅选择field1和field2字段,并进行一个简单的字段运算,生成新的field3。 2.3 数据写入目标系统 处理后的数据可以被发送到任意目标系统,比如另一个Kafka主题或HDFS: yaml sink: type: kafka09 bootstrapServers: "localhost:9092" topic: "output-topic" 或者 yaml sink: type: hdfs path: "hdfs://namenode:8020/output/path" 3. 实现 ExactlyOnce 语义 ExactlyOnce 语义是指在分布式系统中,每条消息只被精确地处理一次,即使在故障恢复后也是如此。在SeaTunnel这个工具里头,我们能够实现这个目标,靠的是把Flink或者其他那些支持“ExactlyOnce”这种严谨语义的计算引擎,与具有事务处理功能的数据源和目标巧妙地搭配起来。就像是玩拼图一样,把这些组件严丝合缝地对接起来,确保数据的精准无误传输。 例如,在与Apache Flink整合时,SeaTunnel可以利用Flink的Checkpoint机制来保证状态一致性及ExactlyOnce语义。同时,SeaTunnel还有个很厉害的功能,就是针对那些支持事务处理的数据源,比如更新到Kafka 0.11及以上版本的,还有目标端如Kafka、能进行事务写入的HDFS,它都能联手计算引擎,确保从头到尾,数据“零丢失零重复”的精准传输,真正做到端到端的ExactlyOnce保证。就像一个超级快递员,确保你的每一份重要数据都能安全无误地送达目的地。 在配置中,开启Flink Checkpoint功能,确保在处理过程中遇到故障时可以从检查点恢复并继续处理,避免数据丢失或重复: yaml engine: type: flink checkpoint: interval: 60s mode: exactly_once 总结来说,借助SeaTunnel灵活强大的流式数据处理能力,结合支持ExactlyOnce语义的计算引擎和其他组件,我们完全可以在实际业务场景中实现高可靠、无重复的数据处理流程。在这一路的“探险”中,我们可不只是见识到了SeaTunnel那实实在在的实用性以及它强大的威力,更是亲身感受到了它给开发者们带来的那种省心省力、安心靠谱的舒爽体验。而随着技术和需求的不断演进,SeaTunnel也将在未来持续优化和完善,为广大用户提供更优质的服务。
2023-05-22 10:28:27
113
夜色朦胧
Saiku
...方案 一、引言 在大数据分析领域,Saiku以其强大的数据可视化和多维数据分析能力广受企业用户的青睐。然而,在真正动手部署的时候,咱们可能会遇到这么个情况:想把Saiku和公司内部的那个LDAP(也就是轻量级目录访问协议)整一块儿,实现单点登录的便利功能,结果却碰到了认证失败的问题。这无疑给我们的工作带来了困扰。这篇文会采用一种边探索边唠嗑的方式,一步步把这个问题掰开了、揉碎了讲明白,并且我还会手把手地带你瞅瞅实例代码,实实在在地演示一下如何把这个棘手的问题给妥妥地解决掉。 二、理解Saiku与LDAP集成 1. LDAP基础介绍 LDAP是一种开源的、分布式的、为用户提供网络目录服务的应用协议。对企业来讲,这玩意儿就像是个超级大管家,能够把所有用户的账号信息一把抓,统一管理起来。这样一来,用户在不同系统间穿梭的时候,验证身份的流程就能变得轻松简单,再也不用像以前那样繁琐复杂了。 2. Saiku与LDAP集成原理 Saiku支持与LDAP集成,从而允许用户使用LDAP中的凭证直接登录到Saiku平台,无需单独在Saiku中创建账户。当你尝试登录Saiku的时候,它会超级贴心地把你输入的用户名和密码打包好,然后嗖的一下子送到LDAP服务器那里去“验明正身”。 三、认证失败常见原因及排查 1. 配置错误 (1)连接参数不准确:确保Saiku配置文件中关于LDAP的相关参数如URL、DN(Distinguished Name)、Base DN等设置正确无误。 properties Saiku LDAP配置示例 ldap.url=ldap://ldap.example.com:389 ldap.basedn=ou=People,dc=example,dc=com ldap.security.principal=uid=admin,ou=Admins,dc=example,dc=com ldap.security.credentials=password (2)过滤器设置不当:检查user.object.class和user.filter属性是否能够正确匹配到LDAP中的用户条目。 2. 权限问题 确保用于验证的LDAP账户有足够的权限去查询用户信息。 3. 网络问题 检查Saiku服务器与LDAP服务器之间的网络连通性。 四、实战调试与解决方案 1. 日志分析 通过查看Saiku和LDAP的日志,我们可以获取更详细的错误信息,例如连接超时、认证失败的具体原因等,从而确定问题所在。 2. 代码层面调试 在Saiku源码中找到处理LDAP认证的部分,如: java DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(bindDN, new String[] { "cn" }); 可以通过添加调试语句或日志输出,实时观察变量状态以及执行过程。 3. 解决方案实施 根据排查结果调整相关配置或修复代码,例如: - 如果是配置错误,修正相应配置并重启Saiku服务; - 如果是权限问题,联系LDAP管理员调整权限; - 若因网络问题,检查防火墙设置或优化网络环境。 五、总结 面对Saiku与LDAP集成认证失败的问题,我们需要从多个角度进行全面排查:从配置入手,细致核查每项参数;利用日志深入挖掘潜在问题;甚至在必要时深入源码进行调试。经过我们一步步实打实的操作,最后肯定能把这个问题妥妥地解决掉,让Saiku和LDAP这对好伙伴之间搭建起一座坚稳的安全认证桥梁。这样一来,企业用户们就能轻轻松松、顺顺利利地进行大数据分析工作了,效率绝对杠杠的!在整个过程中,不断思考、不断尝试,是我们解决问题的关键所在。
2023-10-31 16:17:34
134
雪落无痕
HessianRPC
...是迭代的时候,服务端接口更新优化什么的,简直就是家常便饭。这样一来,就牵扯出一个大问题:当咱们把Hessian服务端改头换面升级之后,怎么才能确保客户端能跟这个新版本的服务端无缝衔接、配合得溜溜的呢?这篇文咱就打算把这个事儿掰开了揉碎了讲讲,并且还会附上一些实实在在的实例代码,让大家一看就懂,一用就会。 1. 版本控制策略 首先,为了保证服务端更新时对客户端的影响降到最低,我们需要建立一套严格的版本控制策略。在设计Hessian服务接口的时候,我们可以像给小宝贝添加成长标签一样,为每个接口或者整个服务设置一个版本号。这样,当服务端内部有了什么新变化、更新迭代时,就像孩子长大了一岁,我们就通过升级这个版本号来区分新旧接口。而客户端呢,就像个聪明的玩家,会根据自己手里的“说明书”(支持的版本)去选择调用哪个合适的接口。 java // 定义带有版本号的Hessian服务接口 public interface MyService { // v1版本的接口 String oldMethod(int arg) throws RemoteException; // v2版本的接口,增加了新的参数 String newMethod(int arg, String newParam) throws RemoteException; } 2. 向后兼容性设计 当服务端新增接口或修改已有接口时,应尽可能保持向后兼容性,避免破坏现有客户端调用。比如,当你添加新的参数时,可以给它预先设定一个默认值。而如果你想删掉或者修改某个参数,只要不影响业务正常运作的那个“筋骨”,就可以保留原来的接口,让老版本的客户端继续舒舒服服地用着,不用着急升级换代。 java // 新版本接口考虑向后兼容 public String newMethod(int arg, String newParam = "default_value") { //... } 3. 双重部署和灰度发布 在实际更新过程中,我们可以通过双重部署及灰度发布的方式来平滑过渡。先部署新版本服务,并让部分用户或流量切换至新版本进行验证测试,确认无误后再逐步扩大范围直至全量替换。 4. 客户端适配升级 对于客户端来说,应对服务端接口变化的主要方式是对自身进行相应的更新和适配: - 动态加载服务接口:客户端可以通过动态加载机制,根据服务端返回的版本信息加载对应的接口实现类,从而实现自动适配新版本服务。 java // 动态加载示例(伪代码) String serviceUrl = "http://server:port/myService"; HessianProxyFactory factory = new HessianProxyFactory(); MyService myService; try { // 获取服务端版本信息 VersionInfo versionInfo = getVersionFromServer(serviceUrl); // 根据版本创建代理对象 if (versionInfo.isV1()) { myService = (MyService) factory.create(MyService.class, serviceUrl + "?version=v1"); } else if (versionInfo.isV2()) { myService = (MyService) factory.create(MyService.class, serviceUrl + "?version=v2"); } } catch (Exception e) { // 错误处理 } // 调用对应版本的方法 String result = myService.newMethod(1, "newParam"); - 客户端版本迭代:对于无法通过兼容性设计解决的重大变更,客户端也需要同步更新以适应新接口。这时候,咱们得好好策划一个详尽的升级计划和方案出来,并且要赶紧给所有客户端开发的大哥们发个消息,让他们麻溜地进行更新工作。 总结起来,要保证Hessian服务端更新后与客户端的无缝对接,关键在于合理的设计和服务管理策略,包括但不限于版本控制、接口向后兼容性设计、双重部署及灰度发布以及客户端的灵活适配升级。在整个过程中,不断沟通、思考和实践,才能确保每一次迭代都平稳顺利地完成。
2023-10-30 17:17:18
495
翡翠梦境
Mahout
...out在推荐系统中的数据模型构建失败探索 一、引言 你是否曾经经历过这样的情况?你的推荐系统在生产环境中突然崩溃,只因为用户对商品进行了一些看似微不足道的操作?如果你的答案是肯定的,那么你可能已经意识到了推荐系统的脆弱性,以及它们对于数据质量的依赖。 在本篇文章中,我们将深入研究推荐系统中最常见的问题之一——数据模型构建失败,并尝试利用Mahout这个强大的开源库来解决这个问题。 二、数据模型构建失败的原因 数据模型构建失败的原因有很多,例如: - 数据质量问题:这可能是由于原始数据集中的错误、缺失值或者噪声引起的。 - 模型选择问题:不同的推荐算法适用于不同类型的数据集,如果选择了不适合的模型,可能会导致模型训练失败。 - 参数调整问题:推荐系统的性能很大程度上取决于模型的参数设置,不恰当的参数设置可能导致模型过拟合或欠拟合。 三、Mahout在数据模型构建失败时的应对策略 3.1 数据清洗与预处理 在我们开始构建推荐模型之前,我们需要对原始数据进行一些基本的清理和预处理操作。这些操作包括去除重复记录、填充缺失值、处理异常值等。下面是一个简单的例子,展示了如何使用Mahout进行数据清洗: java // 创建一个MapReduce任务来读取数据 Job job = new Job(); job.setJarByClass(Mahout.class); job.setMapperClass(CSVInputFormat.class); job.setReducerClass(CSVOutputFormat.class); // 设置输入路径和输出路径 FileInputFormat.addInputPath(job, new Path("input.csv")); FileOutputFormat.setOutputPath(job, new Path("output.csv")); // 运行任务 boolean success = job.waitForCompletion(true); if (success) { System.out.println("Data cleaning and preprocessing complete!"); } else { System.out.println("Data cleaning and preprocessing failed."); } 在这个例子中,我们使用了CSVInputFormat和CSVOutputFormat这两个类来进行数据清洗和预处理。说得更直白点,CSVInputFormat就像是个数据搬运工,它的任务是从CSV文件里把我们需要的数据给拽出来;而CSVOutputFormat呢,则是个贴心的数据管家,它负责把我们已经清洗干净的数据,整整齐齐地打包好,再存进一个新的CSV文件里。 3.2 模型选择和参数调优 选择合适的推荐算法和参数设置是构建成功推荐模型的关键。Mahout提供了许多常用的推荐算法,如协同过滤、基于内容的推荐等。同时呢,它还带来了一整套给力的工具,专门帮我们微调模型的参数,让模型的表现力更上一层楼。 以下是一个简单的例子,展示了如何使用Mahout的ALS(Alternating Least Squares)算法来构建推荐模型: java // 创建一个新的推荐器 RecommenderSystem recommenderSystem = new RecommenderSystem(); // 使用 ALS 算法来构建推荐模型 Recommender alsRecommender = new MatrixFactorizationRecommender(new ItemBasedUserCF(alternatingLeastSquares(10), userItemRatings)); recommenderSystem.addRecommender(alsRecommender); // 进行参数调优 alsRecommender.setParameter(alsRecommender.getParameter(ALS.RANK), 50); // 尝试增加隐藏层维度 在这个例子中,我们首先创建了一个新的推荐器,并使用了ALS算法来构建推荐模型。然后,我们对模型的参数进行了调优,尝试增加了隐藏层的维度。 3.3 数据监控与故障恢复 最后,我们需要建立一套完善的数据监控体系,以便及时发现并修复数据模型构建失败的问题。Mahout这玩意儿,它帮我们找到了一个超简单的方法,就是利用Hadoop的Streaming API,能够实时地、像看直播一样掌握推荐系统的运行情况。 以下是一个简单的例子,展示了如何使用Mahout和Hadoop的Streaming API来实现实时监控: java // 创建一个MapReduce任务来监控数据 Job job = new Job(); job.setJarByClass(Mahout.class); job.setMapperClass(StreamingInputFormat.class); job.setReducerClass(StreamingOutputFormat.class); // 设置输入路径和输出路径 FileInputFormat.addInputPath(job, new Path("input.csv")); FileOutputFormat.setOutputPath(job, new Path("output.csv")); // 运行任务 boolean success = job.waitForCompletion(true); if (success) { System.out.println("Data monitoring and fault recovery complete!"); } else { System.out.println("Data monitoring and fault recovery failed."); } 在这个例子中,我们使用了StreamingInputFormat和StreamingOutputFormat这两个类来进行数据监控。换句话说,StreamingInputFormat这小家伙就像是个专门从CSV文件里搬运数据的勤快小工,而它的搭档StreamingOutputFormat呢,则负责把我们监控后的结果打包整理好,再稳稳当当地存放到新的CSV文件中去。 四、结论 本文介绍了推荐系统中最常见的问题之一——数据模型构建失败的原因,并提供了解决这个问题的一些策略,包括数据清洗与预处理、模型选择和参数调优以及数据监控与故障恢复。虽然这些问题确实让人头疼,不过别担心,只要我们巧妙地运用那个超给力的开源神器Mahout,就能让推荐系统的运行既稳如磐石又准得惊人,妥妥提升它的稳定性和准确性。
2023-01-30 16:29:18
121
风轻云淡-t
Apache Pig
...并行处理的艺术 在大数据的世界中,Apache Pig是一个强大的工具,它以SQL-like的脚本语言——Pig Latin,为我们提供了一种高效、灵活的方式来处理大规模的数据集。这篇文咱要深度挖掘一下怎么用Apache Pig这个神器进行并行处理,而且为了让大伙儿能更接地气地体验到它的魔力,我们会辅以实例代码,让大家亲自感受一下这货到底有多牛! 1. Apache Pig简介 Apache Pig是一个高层次的数据流处理平台,设计初衷是为了简化Hadoop生态系统的复杂性,尤其是对于那些需要对大量数据进行复杂转换和分析的任务。Pig Latin在Pig这个大家伙里可是心脏般的存在,它让咱们能够用一种更简单的方式编写出那些复杂的数据处理程序。想象一下,你写好代码后,Pig Latin就像个魔术师,嗖嗖几下就把你的程序变形成一系列MapReduce任务,然后稳稳当当地在Hadoop集群上跑起来。这样一来,大规模并行处理就不再是难题,而是轻松实现了! 2. 并行处理原理 Pig利用Hadoop的分布式计算框架,在底层自动将Pig Latin脚本转换为多个MapReduce任务,这些任务能够在多台机器上同时执行,大大提高了数据处理速度。换句话说,当你在捣鼓Pig Latin来设定一个数据处理流程时,其实就是在给一个并行处理的智慧路径画地图。Pig这个小机灵鬼呢,会超级聪明地把你的流程大卸八块,然后妥妥地分配到各个节点上执行起来。 3. 使用Pig Latin进行并行处理实战 示例一:数据加载与过滤 假设我们有一个大型的CSV文件存储在HDFS上,我们想找出所有年龄大于30岁的用户记录: pig -- 加载数据 data = LOAD 'hdfs://path/to/user_data.csv' USING PigStorage(',') AS (name:chararray, age:int, gender:chararray); -- 过滤出年龄大于30岁的用户 adults = FILTER data BY age > 30; -- 存储结果 STORE adults INTO 'hdfs://path/to/adults_data'; 上述代码中,LOAD操作首先将数据从HDFS加载到Pig中,接着FILTER操作会在集群内的所有节点并行执行,筛选出符合条件的记录,最后将结果保存回HDFS。 示例二:分组与聚合 现在,我们进一步对数据进行分组统计,比如按性别统计各年龄段的人数: pig -- 对数据进行分组并统计 grouped_data = GROUP adults BY gender; age_counts = FOREACH grouped_data GENERATE group, COUNT(adults), AVG(adults.age); -- 输出结果 DUMP age_counts; 这里,GROUP操作会对数据进行分组,然后在每个分组内部并行执行COUNT和AVG函数,得出每个性别的总人数以及平均年龄,整个过程充分利用了集群的并行处理能力。 4. 思考与理解 在实际操作过程中,你会发现Apache Pig不仅简化了并行编程的难度,同时也提供了丰富的内置函数和运算符,使得数据分析工作变得更加轻松。这种基于Pig Latin的声明式编程方式,让我们能够更关注于“要做什么”,而非“如何做”。每当你敲下一个Pig Latin命令,就像在指挥一个交响乐团,它会被神奇地翻译成一连串MapReduce任务。而在这个舞台背后,有个低调的“大块头”Hadoop正在卖力干活,悄无声息地扛起了并行处理的大旗。这样一来,我们开发者就能一边悠哉享受并行计算带来的飞速快感,一边又能摆脱那些繁琐复杂的并行编程细节,简直不要太爽! 总结起来,Apache Pig正是借助其强大的Pig Latin语言及背后的并行计算机制,使得大规模数据处理变得如烹小鲜般简单而高效。无论是处理基础的数据清洗、转换,还是搞定那些烧脑的统计分析,Pig这家伙都能像把刀切黄油那样轻松应对,展现出一种无人能敌的独特魅力。因此,熟练掌握Apache Pig,无疑能让你在大数据领域更加得心应手,挥洒自如。
2023-02-28 08:00:46
497
晚秋落叶
转载文章
...构造函数以及改进了与Java平台互操作时的性能表现。 在实际项目中,Google推荐开发者优先使用原生类型数组以提升性能,尤其是在处理大量数据或高性能要求的应用场景。例如,在游戏开发中,通过Kotlin的IntArray优化图形渲染的数据结构可以有效减少内存分配和GC压力,从而提升整体流畅度。 此外,对于多维数组的处理,Kotlin提供了一种更为灵活且易于理解的解构声明语法,允许开发者更直观地访问和操作多级嵌套数组中的元素。同时,结合Kotlin的高阶函数如map、filter等,可以在不引入额外复杂度的情况下对数组进行复杂的变换操作。 深入研究Kotlin官方文档和社区论坛,你会发现更多有关数组的最佳实践案例,包括如何结合协程进行异步数组操作,以及如何利用Kotlin的扩展函数简化数组操作代码。而在机器学习或大数据处理领域,利用Kotlin的Numpy-like库koma可以实现类似Python Numpy对多维数组的强大支持,这对于科学计算和数据分析尤为重要。 总之,掌握Kotlin数组的各种特性并适时关注其最新进展,能够帮助开发者在日常编码工作中更加游刃有余,提高应用程序的运行效率和代码可读性。
2023-03-31 12:34:25
66
转载
Hive
... Hive:在大数据时代中挖掘并行计算的力量 一、引言 并行计算的诱惑与挑战 在大数据时代,数据处理的速度与效率成为了衡量一个系统是否强大的关键指标之一。嘿,你知道Hive吗?这家伙可是Apache家族里的宝贝疙瘩,专门用来处理大数据的仓库工具!它最大的亮点就是用的那套HQL,超级像咱们平时玩的SQL,简单易懂,方便操作。这玩意儿一出,分析海量数据就跟翻书一样轻松,简直是数据分析师们的福音啊!哎呀,你知道的,现在数据就像雨后春笋一样,长得飞快,复杂程度也跟上去了。在这大背景下,怎么在Hive里用好并行计算这个神器,就成了咱们提高数据处理速度的大秘密武器了。就像是在厨房里,你得知道怎么合理安排人力物力,让每个步骤都能高效进行,这样才能做出最美味的佳肴。在大数据的世界里,这不就是个道理嘛! 二、理解并行计算在Hive中的应用 并行计算,即通过多个处理器或计算机同时执行任务,可以极大地缩短数据处理时间。在Hive中,这种并行能力主要体现在以下两个方面: 1. 分布式文件系统(DFS)支持 Hive能够将数据存储在分布式文件系统如HDFS上,这样数据的读取和写入就可以被多个节点同时处理,大大提高了数据访问速度。 2. MapReduce执行引擎 Hive的核心执行引擎是MapReduce,它允许任务被拆分成多个小任务并行执行,从而加速了数据处理流程。 三、案例分析 优化Hive查询性能的策略 为了更好地利用Hive的并行计算能力,我们可以采取以下几种策略来优化查询性能: 1. 合理使用分区和表结构 sql CREATE TABLE sales ( date STRING, product STRING, quantity INT ) PARTITIONED BY (year INT, month INT); 分区操作能帮助Hive在执行查询时快速定位到特定的数据集,从而减少扫描的文件数量,提高查询效率。 2. 利用索引增强查询性能 sql CREATE INDEX idx_sales_date ON sales (date); 索引可以显著加快基于某些列的查询速度,特别是在进行过滤和排序操作时。 3. 优化查询语句 - 避免使用昂贵的函数和复杂的子查询。 - 使用EXPLAIN命令预览查询计划,识别瓶颈并进行调整。 sql EXPLAIN SELECT FROM sales WHERE year = 2023 AND month = 5; 4. 批处理与实时查询分离 对于频繁执行的查询,考虑将其转换为更高效的批处理作业,而非实时查询。 四、实践与经验分享 在实际操作中,我们发现以下几点经验尤为重要: - 数据预处理:确保数据在导入Hive前已经进行了清洗和格式化,减少无效数据的处理时间。 - 定期维护:定期清理不再使用的数据和表,以及更新索引,保持系统的高效运行。 - 监控与调优:利用Hive Metastore提供的监控工具,持续关注查询性能,并根据实际情况调整配置参数。 五、结论 并行计算与Hive的未来展望 随着大数据技术的不断发展,Hive在并行计算领域的潜力将进一步释放。哎呀,兄弟!咱们得好好调整数据存档的布局,还有那些查询命令和系统的设定,这样才能让咱们的数据处理快如闪电,用户体验棒棒哒!到时候,用咱们的服务就跟喝着冰镇可乐一样爽,那叫一个舒坦啊!哎呀,你知道不?就像咱们平时用的工具箱里又添了把更厉害的瑞士军刀,那就是Apache Drill这样的新技术。这玩意儿一出现,Hive这个大数据分析的家伙就更牛了,能干的事情更多,效率也更高,就像开挂了一样。它现在不仅能快如闪电地处理数据,还能像变魔术一样,根据我们的需求变出各种各样的分析结果。这下子,咱们做数据分析的时候,可就轻松多了! --- 本文旨在探讨Hive如何通过并行计算能力提升数据处理效率,通过具体实例展示了如何优化Hive查询性能,并分享了实践经验。希望这些内容能对您在大数据分析领域的工作提供一定的启发和帮助。
2024-09-13 15:49:02
35
秋水共长天一色
SpringBoot
...业开始采用NoSQL数据库作为其数据存储的核心系统。其中,MongoDB凭借其灵活的数据模型、强大的查询能力和易于使用的API,成为了许多企业的首选。在众多的NoSQL数据库里头,SpringBoot和MongoDB的联手合作可是相当普遍,而且技术上也相当成熟,可以说是其中一对黄金搭档啦!这篇文稿,咱们要手把手地教你如何在SpringBoot这个大家伙里头接入MongoDB数据库,并且还会举些实实在在的例子,演示一些你可能会经常用到的操作步骤,保证接地气儿,不玩虚的。 2. 环境搭建 在开始集成之前,我们需要先准备好相应的开发环境。首先,兄弟姐妹们,咱得先下载并安装Java运行环境。版本上没硬性要求,不过我强烈建议你们选择最新潮的那个——Java 8或者更新更高的版本,这样用起来更溜~然后,我们需要下载并安装SpringBoot和Maven这两个工具。SpringBoot可以为我们提供一个快速构建Web应用的基础框架,而Maven则可以帮助我们管理项目的依赖关系。 3. 创建SpringBoot项目 接下来,我们可以开始创建我们的SpringBoot项目。首先,打开命令行工具,并进入你要存放项目的位置。然后,输入以下命令来创建一个新的SpringBoot项目: bash mvn archetype:generate -DgroupId=com.example -DartifactId=springboot-mongoapp -DarchetypeArtifactId= spring-boot-starter-parent -DinteractiveMode=false 这行命令的意思是使用Maven的archetype功能来生成一个新的SpringBoot项目,该项目的组ID为com.example, artifactID为springboot-mongoapp,父依赖为spring-boot-starter-parent。这个命令会自动为你创建好所有的项目文件和目录结构,包括pom.xml和src/main/java/com/example/springbootmongoapp等文件。 4. 配置SpringBoot和MongoDB 在创建好项目之后,我们需要进行一些配置工作。首先,我们需要在pom.xml文件中添加SpringDataMongoDB的依赖: xml org.springframework.boot spring-boot-starter-data-mongodb 这行代码的意思是我们需要使用SpringDataMongoDB来处理MongoDB的相关操作。然后,我们需要在application.properties文件中添加MongoDB的连接信息: properties spring.data.mongodb.uri=mongodb://localhost:27017/mydb 这行代码的意思是我们的MongoDB服务器位于本地主机的27017端口上,且数据库名为mydb。 5. 使用MongoTemplate操作MongoDB 在配置完成后,我们就可以开始使用MongoTemplate来操作MongoDB了。MongoTemplate是SpringDataMongoDB提供的一个类,它可以帮助我们执行各种数据库操作。下面是一些基本的操作示例: java @Autowired private MongoTemplate mongoTemplate; public void insert(String collectionName, String id, Object entity) { mongoTemplate.insert(entity, collectionName); } public List find(String collectionName, Query query) { return mongoTemplate.find(query, Object.class, collectionName); } 6. 使用Repository操作MongoDB 除了MongoTemplate之外,SpringDataMongoDB还提供了Repository接口,它可以帮助我们更加方便地进行数据库操作。我们完全可以把这个接口“继承”下来,然后自己动手编写几个核心的方法,就像是插入数据、查找信息、更新记录、删除项目这些基本操作,让它们各司其职,活跃在我们的程序里。下面是一个简单的示例: java @Repository public interface UserRepository extends MongoRepository { User findByUsername(String username); void deleteByUsername(String username); default void save(User user) { if (user.getId() == null) { user.setId(UUID.randomUUID().toString()); } super.save(user); } @Query(value = "{'username':?0}") List findByUsername(String username); } 7. 总结 总的来说,SpringBoot与MongoDB的集成是非常简单和便捷的。只需要几步简单的配置,我们就可以使用SpringBoot的强大功能来操作MongoDB。而且你知道吗,SpringDataMongoDB这家伙还藏着不少好东西嘞,像数据映射、查询、聚合这些高级功能,全都是它的拿手好戏。这样一来,我们开发应用程序就能又快又高效,简直像是插上了小翅膀一样飞速前进!所以,如果你正在琢磨着用NoSQL数据库来搭建你的数据存储方案,那我真心实意地拍胸脯推荐你试试SpringBoot配上MongoDB这个黄金组合,准保不会让你失望!
2023-04-09 13:34:32
76
岁月如歌-t
Logstash
...csearch:实时数据处理的黄金搭档 嘿,朋友们!今天我要带大家走进一个非常有趣的技术领域——Logstash与Elasticsearch的结合。这俩在大数据处理界可是响当当的角色,特别是在实时索引优化这块,简直绝了!想象一下,你正面对着一大堆日志数据,每天都得迅速搞定它们的分析和查找,这时候,Logstash加上Elasticsearch简直就是你的超级英雄搭档,简直不要太好用! 1.1 什么是Logstash? Logstash 是一个开源的数据收集引擎,它能够从多个来源采集数据,然后进行转换,最后输出到各种存储系统中。它的设计初衷就是用来处理日志和事件数据的,但其实它的能力远不止于此。这家伙挺能来事儿的,不仅能搞定各种输入插件——比如文件啊、网页数据啊、数据库啥的,还能用过滤插件整点儿花样,比如说正则表达式匹配或者修改字段之类的。最后,它还支持不少输出插件,比如往Elasticsearch或者Kafka里面扔数据,简直不要太方便!这种灵活性使得Logstash成为了处理复杂数据流的理想选择。 1.2 Elasticsearch:实时搜索与分析的利器 Elasticsearch 是一个基于Lucene构建的开源分布式搜索引擎,它提供了强大的全文搜索功能,同时也支持结构化搜索、数值搜索以及地理空间搜索等多种搜索类型。此外,Elasticsearch还拥有出色的实时分析能力,这得益于其独特的倒排索引机制。当你将数据导入Elasticsearch后,它会自动对数据进行索引,从而大大提高了查询速度。 2. 实时索引优化 让数据飞起来 现在我们已经了解了Logstash和Elasticsearch各自的特点,接下来就让我们看看如何通过它们来实现高效的实时索引优化吧! 2.1 数据采集与预处理 首先,我们需要利用Logstash从各种数据源采集数据。好嘞,咱们换个说法:比如说,我们要从服务器的日志里挖出点儿有用的东西,就像找宝藏一样,目标就是那些访问时间、用户ID和请求的网址这些信息。我们可以用Filebeat这个工具来读取日志文件,然后再用Grok这个插件来解析这些数据,让信息变得更清晰易懂。下面是一个具体的配置示例: yaml input { file { path => "/var/log/nginx/access.log" start_position => "beginning" } } filter { grok { match => { "message" => "%{COMBINEDAPACHELOG}" } } } 这段配置告诉Logstash,从/var/log/nginx/access.log这个路径下的日志文件开始读取,并使用Grok插件中的COMBINEDAPACHELOG模式来解析每一行日志内容。这样子一来,原始的文本信息就被拆成了一个个有组织的小块儿,给接下来的处理铺平了道路,简直不要太方便! 2.2 高效索引策略 一旦数据被Logstash处理完毕,下一步就是将其导入Elasticsearch。为了确保索引操作尽可能高效,我们可以采取一些策略: - 批量处理:减少网络往返次数,提高吞吐量。 - 动态映射:允许Elasticsearch根据文档内容自动创建字段类型,简化索引管理。 - 分片与副本:合理设置分片数量和副本数量,平衡查询性能与集群稳定性。 下面是一个简单的Logstash输出配置示例,演示了如何将处理后的数据批量发送给Elasticsearch: yaml output { elasticsearch { hosts => ["localhost:9200"] index => "nginx-access-%{+YYYY.MM.dd}" document_type => "_doc" user => "elastic" password => "changeme" manage_template => false template => "/path/to/template.json" template_name => "nginx-access" template_overwrite => true flush_size => 5000 idle_flush_time => 1 } } 在这段配置中,我们设置了批量大小为5000条记录,以及空闲时间阈值为1秒,这意味着当达到这两个条件之一时,Logstash就会将缓冲区内的数据一次性发送至Elasticsearch。此外,我还指定了自定义的索引模板,以便更好地控制字段映射规则。 3. 实战案例 打造高性能日志分析平台 好了,理论讲得差不多了,接下来让我们通过一个实际的例子来看看这一切是如何运作的吧! 假设你是一家电商网站的运维工程师,最近你们网站频繁出现访问异常的问题,客户投诉不断。为了找出问题根源,你需要对Nginx服务器的日志进行深入分析。幸运的是,你们已经部署了Logstash和Elasticsearch作为日志处理系统。 3.1 日志采集与预处理 首先,我们需要确保Logstash能够正确地从Nginx服务器上采集到所有相关的日志信息。根据上面说的设置,我们可以搞一个Logstash配置文件,用来从特定的日志文件里扒拉出重要的信息。嘿,为了让大家看日志的时候能更轻松明了,我们可以加点小技巧,比如说统计每个用户逛网站的频率,或者找出那些怪怪的访问模式啥的。这样一来,信息就一目了然啦! 3.2 索引优化与查询分析 接下来,我们将这些处理后的数据发送给Elasticsearch进行索引存储。有了合适的索引设置,就算同时来一大堆请求,我们的查询也能嗖嗖地快,不会拖泥带水的。比如说,在上面那个输出配置的例子里面,我们调高了批量处理的门槛,同时把空闲时间设得比较短,这样就能大大加快数据写入的速度啦! 一旦数据被成功索引,我们就可以利用Elasticsearch的强大查询功能来进行深度分析了。比如说,你可以写个DSL查询,找出最近一周内访问量最大的10个页面;或者,你还可以通过用户ID捞出某个用户的操作记录,看看能不能从中发现问题。 4. 结语 拥抱变化,不断探索 通过以上介绍,相信大家已经对如何使用Logstash与Elasticsearch实现高效的实时索引优化有了一个全面的认识。当然啦,技术这东西总是日新月异的,所以我们得保持一颗好奇的心,不停地学新技术,这样才能更好地迎接未来的各种挑战嘛! 希望这篇文章能对你有所帮助,如果你有任何疑问或建议,欢迎随时留言交流。让我们一起加油,共同成长!
2024-12-17 15:55:35
41
追梦人
转载文章
...色职责是把需求或产品实现为用户可用的软件产品。 此职位为执行级别。另外因为经验较少,一般需要求助别人,或与别人一起完(ban)成(zhuan)一个任务。 此阶段大概要经历3年,程序员的职责如下: 1、对项目经理负责,负责软件项目的详细设计、编码和内部测试的组织实施。 2、协助项目经理和相关人员同客户进行沟通,保持良好的客户关系。 3、参与需求调研、项目可行性分析、技术可行性分析和需求分析。 4、熟悉并熟练掌握交付软件部开发的软件项目的相关软件技术。 5、负责向项目经理及时反馈软件开发中的情况,并根据实际情况提出改进建议。 6、负责对业务领域内的技术发展动态进行分析研究。 高级程序员 高级程序员学名,工程师。 到了这个level,英文名可改叫做 engineer 或 developer。此时你的功力开始增强,这与你平时的积累努力是分不开的,祝贺你~ 此时的你不仅可以完成任务,开始注重代码的质量,能够写出工业级的代码。你的经验可胜任模块级的系统设计,承担完成较为复杂的技术,能有效的自我管理,有帮助别人快速解决问题(trouble shooting)的能力。 此阶段你需要经历到7、8年左右的体验,中间要经历一段深刻自我历练的过程。 有时给人致命一击其实是心里的小蟊贼。一般人在5年前后遇到一个门槛,碰到天花板+彷徨期,或者你打心眼里不在喜欢编程,可尝试转为其它角色,如产品经理,售前售后支持等岗位,也不失为好选择。 当我们熬过这段儿,就会“山随平野尽,江入大荒流“,渐入佳境矣。 高级程序员定义软件功能、做开发计划推进和管理。可以带几个个帮手把产品规划的功能实现,你是团队中的”大手“,遇到难题也是你亲自攻艰克难。 所以,一个高级程序员,他的职责很清晰: 1、负责产品核心复杂功能的方案设计、编码实现 2、负责疑难BUG分析诊断、攻关解决 架构师 到了架构师级别,想必你已经学会降龙十八掌,可登堂入世,成为一位准(lao)专(you)家(tiao)。 我们大喊声:“单打独斗,老衲谁也不惧!“,遂开始领导一众技术高手,指点武功,来设计和完成一个系统,大多是分布式,高并发的系统架构平台。 架构师的任务是为公司产品的业务问题提供高质量技术解决方案,主要着眼于系统的"技术实现" 。 架构师的主要分类: 可能每条产品线都设置了架构师,也可能多条生产品线的的后端是由一个架构师设计的平台提供,所以架构师也是有所不同的,其分类如下: 软件架构师 信息架构师 网站架构师 其主要职责如下: 1、需求分析:“知彼”有时比“知已”还重要。管理市场,产品等的需求,确立关键需求。坚持技术上的优秀与需求的愿景统一,提升技术负债意识,提供技术选项,风险预判,工期等解决方案。 2、架构设计:在产品功能中抽取中非功能的需求,由关键需求变成概念型架构。列出功能树,分层治之,如用户界面层、系统交互层,数据管理层。达成高扩展,高可用,高性能,高安全,易运维,易部署,易接入等能力。 3、功能设计与实现:对架构设计的底层代码级别实现。如公共核心类,接口实现,应用发现规则、接口变更等。 技术经理 人生就是不断上升的过程,你已经到达经理的层次了。如今的你,需要不断提高领导力,需要定期召开团队会议讨论问题。 首先我们要更加自信,在工作中显示自己的功力,给讲话增添力量。如:“本次项目虽然有很大的困难,我们也需苦战到底。当然示先垂范,身先士卒,方能成功!” 技术经理有时候也可能叫系统分析员,一些小公司可能会整个公司或者部门有一个技术经理。技术经理承担的角色主要是系统分析、架构搭建、系统构建、代 码走查等工作,如果说项目经理是总统,那么技术经理就是总理。当然不是所有公司都是这样的,有些公司项目经理是不管技术团队的,只做需求、进度和同客户沟 通,那么这个时候的项目经理就好像工厂里的跟单人员了,这种情况在外包公司比较多。对于技术经理来说,着重于技术方面,你需要知道某种功能用哪些技术合 适,需要知道某项功能需要多长的开发时间等。同时,技术经理也应该承担提高团队整体技术水平的工作。 你需要和大家站在一起,因为人们也都有解决问题的能力,更需要有以下的能力与责任: 1、任务管理:开发工作量评估、定立开发流程、分配和追踪开发任务 2、质量管理:代码review、开发风险判断/报告/协调解决 3、效率提升:代码底层研发和培训、最佳代码实践规范总结与推广、自动化生产工具、自动化部署工具 4、技术能力提升:招聘面试、试题主拟、新人指导、项目复盘与改进 技术总监 如果一个研发团队超过20人,有多条产品线或业务量很大,这时已经有多个技术经理在负责每个业务,这时需要一位技术总监。 主要职责: 1、组建平台研发部,与架构师共建软件公共平台,方便各条产品业务线研发。 2、通过技术平台、通过高一层的职权,管理和协调公司各个部门与本部门各条线。现在每个产品线都应该有合格的技术经理和高级程序员。 结语:我们相信,每个人都能成为IT大神。现在开始,找个师兄带你入门,让你的学习之路不再迷茫。 这里推荐我们的前端学习交流圈:784783012,里面都是学习前端的从最基础的HTML+CSS+JS【炫酷特效,游戏,插件封装,设计模式】到移动端HTML5的项目实战的学习资料都有整理,送给每一位前端小伙伴。 最新技术,与企业需求同步。好友都在里面学习交流,每天都会有大牛定时讲解前端技术! 点击:前端技术分享 本篇文章为转载内容。原文链接:https://blog.csdn.net/webDk/article/details/88917912。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2024-05-10 13:13:48
755
转载
转载文章
...自然》杂志报道了基于Transformer架构的预训练模型如BERT、RoBERTa等,在中文分词任务上取得的重大突破。通过预训练和微调的方式,这些模型能够在不依赖复杂分词算法的情况下实现高精度的词语切分,并且在长文本理解和语义分析上有显著优势。 2. 开源工具对比及应用场景:除了jieba之外,还有HanLP、LTP(哈工大语言技术平台)等优秀的中文分词开源工具。读者可以通过对比它们在不同场景下的性能表现,了解各自的优缺点以及如何根据实际需求选择合适的分词工具。例如,在处理大规模文本数据集时,考量速度、准确率以及资源消耗等因素至关重要。 3. 行业应用实例剖析:在新闻资讯、搜索引擎优化、社交媒体监控等领域,高效的中文分词技术具有广泛的应用价值。阿里巴巴、腾讯等企业在其产品中就广泛应用了此类技术,用于用户行为分析、智能推荐系统构建等方面。通过研究这些真实案例,可以深入了解jieba等分词工具在解决实际问题时所发挥的关键作用。 4. 学术研究与发展趋势:查阅最新的自然语言处理学术论文,可以发现对于中文分词的研究正逐渐从规则驱动转向数据驱动,并尝试结合多种上下文信息进行更精细化的词语切分。同时,跨语言模型的出现也为中文分词带来了新的挑战与机遇,比如探讨如何利用多语言模型对未登录词或新词进行有效识别和处理。 综上所述,关于jieba中文分词组件的延伸阅读,可以从深度学习技术在分词任务上的前沿发展、同类开源工具比较、具体行业应用案例以及学术研究趋势等多个维度展开,以全面把握这一领域的现状与未来发展方向。
2023-12-02 10:38:37
500
转载
转载文章
...T Identity实现应用程序的用户管理,以及实现应用程序的认证与授权等相关技术,译者希望本系列教程能成为掌握ASP.NET Identity技术的一份完整而有价值的资料。读者若是能够按照文章的描述,一边阅读、一边实践、一边理解,定能有意想不到的巨大收获!希望本系列博文能够得到广大园友的高度推荐。 15 Advanced ASP.NET Identity 15 ASP.NET Identity高级技术 In this chapter, I finish my description of ASP.NET Identity by showing you some of the advanced features it offers. I demonstrate how you can extend the database schema by defining custom properties on the user class and how to use database migrations to apply those properties without deleting the data in the ASP.NET Identity database. I also explain how ASP.NET Identity supports the concept of claims and demonstrates how they can be used to flexibly authorize access to action methods. I finish the chapter—and the book—by showing you how ASP.NET Identity makes it easy to authenticate users through third parties. I demonstrate authentication with Google accounts, but ASP.NET Identity has built-in support for Microsoft, Facebook, and Twitter accounts as well. Table 15-1 summarizes this chapter. 本章将完成对ASP.NET Identity的描述,向你展示它所提供的一些高级特性。我将演示,你可以扩展ASP.NET Identity的数据库架构,其办法是在用户类上定义一些自定义属性。也会演示如何使用数据库迁移,这样可以运用自定义属性,而不必删除ASP.NET Identity数据库中的数据。还会解释ASP.NET Identity如何支持声明(Claims)概念,并演示如何将它们灵活地用来对动作方法进行授权访问。最后向你展示ASP.NET Identity很容易通过第三方部件来认证用户,以此结束本章以及本书。将要演示的是使用Google账号认证,但ASP.NET Identity对于Microsoft、Facebook以及Twitter账号,都有内建的支持。表15-1是本章概要。 Table 15-1. Chapter Summary 表15-1. 本章概要 Problem 问题 Solution 解决方案 Listing 清单号 Store additional information about users. 存储用户的附加信息 Define custom user properties. 定义自定义用户属性 1–3, 8–11 Update the database schema without deleting user data. 更新数据库架构而不删除用户数据 Perform a database migration. 执行数据库迁移 4–7 Perform fine-grained authorization. 执行细粒度授权 Use claims. 使用声明(Claims) 12–14 Add claims about a user. 添加用户的声明(Claims) Use the ClaimsIdentity.AddClaims method. 使用ClaimsIdentity.AddClaims方法 15–19 Authorize access based on claim values. 基于声明(Claims)值授权访问 Create a custom authorization filter attribute. 创建一个自定义的授权过滤器注解属性 20–21 Authenticate through a third party. 通过第三方认证 Install the NuGet package for the authentication provider, redirect requests to that provider, and specify a callback URL that creates the user account. 安装认证提供器的NuGet包,将请求重定向到该提供器,并指定一个创建用户账号的回调URL。 22–25 15.1 Preparing the Example Project 15.1 准备示例项目 In this chapter, I am going to continue working on the Users project I created in Chapter 13 and enhanced in Chapter 14. No changes to the application are required, but start the application and make sure that there are users in the database. Figure 15-1 shows the state of my database, which contains the users Admin, Alice, Bob, and Joe from the previous chapter. To check the users, start the application and request the /Admin/Index URL and authenticate as the Admin user. 本章打算继续使用第13章创建并在第14章增强的Users项目。对应用程序无需做什么改变,但需要启动应用程序,并确保数据库中有一些用户。图15-1显示了数据库的状态,它含有上一章的用户Admin、Alice、Bob以及Joe。为了检查用户,请启动应用程序,请求/Admin/Index URL,并以Admin用户进行认证。 Figure 15-1. The initial users in the Identity database 图15-1. Identity数据库中的最初用户 I also need some roles for this chapter. I used the RoleAdmin controller to create roles called Users and Employees and assigned the users to those roles, as described in Table 15-2. 本章还需要一些角色。我用RoleAdmin控制器创建了角色Users和Employees,并为这些角色指定了一些用户,如表15-2所示。 Table 15-2. The Types of Web Forms Code Nuggets 表15-2. 角色及成员(作者将此表的标题写错了——译者注) Role 角色 Members 成员 Users Alice, Joe Employees Alice, Bob Figure 15-2 shows the required role configuration displayed by the RoleAdmin controller. 图15-2显示了由RoleAdmin控制器所显示出来的必要的角色配置。 Figure 15-2. Configuring the roles required for this chapter 图15-2. 配置本章所需的角色 15.2 Adding Custom User Properties 15.2 添加自定义用户属性 When I created the AppUser class to represent users in Chapter 13, I noted that the base class defined a basic set of properties to describe the user, such as e-mail address and telephone number. Most applications need to store more information about users, including persistent application preferences and details such as addresses—in short, any data that is useful to running the application and that should last between sessions. In ASP.NET Membership, this was handled through the user profile system, but ASP.NET Identity takes a different approach. 我在第13章创建AppUser类来表示用户时曾做过说明,基类定义了一组描述用户的基本属性,如E-mail地址、电话号码等。大多数应用程序还需要存储用户的更多信息,包括持久化应用程序爱好以及地址等细节——简言之,需要存储对运行应用程序有用并且在各次会话之间应当保持的任何数据。在ASP.NET Membership中,这是通过用户资料(User Profile)系统来处理的,但ASP.NET Identity采取了一种不同的办法。 Because the ASP.NET Identity system uses Entity Framework to store its data by default, defining additional user information is just a matter of adding properties to the user class and letting the Code First feature create the database schema required to store them. Table 15-3 puts custom user properties in context. 因为ASP.NET Identity默认是使用Entity Framework来存储其数据的,定义附加的用户信息只不过是给用户类添加属性的事情,然后让Code First特性去创建需要存储它们的数据库架构即可。表15-3描述了自定义用户属性的情形。 Table 15-3. Putting Cusotm User Properties in Context 表15-3. 自定义用户属性的情形 Question 问题 Answer 回答 What is it? 什么是自定义用户属性? Custom user properties allow you to store additional information about your users, including their preferences and settings. 自定义用户属性让你能够存储附加的用户信息,包括他们的爱好和设置。 Why should I care? 为何要关心它? A persistent store of settings means that the user doesn’t have to provide the same information each time they log in to the application. 设置的持久化存储意味着,用户不必每次登录到应用程序时都提供同样的信息。 How is it used by the MVC framework? 在MVC框架中如何使用它? This feature isn’t used directly by the MVC framework, but it is available for use in action methods. 此特性不是由MVC框架直接使用的,但它在动作方法中使用是有效的。 15.2.1 Defining Custom Properties 15.2.1 定义自定义属性 Listing 15-1 shows how I added a simple property to the AppUser class to represent the city in which the user lives. 清单15-1演示了如何给AppUser类添加一个简单的属性,用以表示用户生活的城市。 Listing 15-1. Adding a Property in the AppUser.cs File 清单15-1. 在AppUser.cs文件中添加属性 using System;using Microsoft.AspNet.Identity.EntityFramework;namespace Users.Models { public enum Cities {LONDON, PARIS, CHICAGO}public class AppUser : IdentityUser {public Cities City { get; set; } }} I have defined an enumeration called Cities that defines values for some large cities and added a property called City to the AppUser class. To allow the user to view and edit their City property, I added actions to the Home controller, as shown in Listing 15-2. 这里定义了一个枚举,名称为Cities,它定义了一些大城市的值,另外给AppUser类添加了一个名称为City的属性。为了让用户能够查看和编辑City属性,给Home控制器添加了几个动作方法,如清单15-2所示。 Listing 15-2. Adding Support for Custom User Properties in the HomeController.cs File 清单15-2. 在HomeController.cs文件中添加对自定义属性的支持 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models;namespace Users.Controllers {public class HomeController : Controller {[Authorize]public ActionResult Index() {return View(GetData("Index"));}[Authorize(Roles = "Users")]public ActionResult OtherAction() {return View("Index", GetData("OtherAction"));}private Dictionary<string, object> GetData(string actionName) {Dictionary<string, object> dict= new Dictionary<string, object>();dict.Add("Action", actionName);dict.Add("User", HttpContext.User.Identity.Name);dict.Add("Authenticated", HttpContext.User.Identity.IsAuthenticated);dict.Add("Auth Type", HttpContext.User.Identity.AuthenticationType);dict.Add("In Users Role", HttpContext.User.IsInRole("Users"));return dict;} [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;await UserManager.UpdateAsync(user);return View(user);}private AppUser CurrentUser {get {return UserManager.FindByName(HttpContext.User.Identity.Name);} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } I added a CurrentUser property that uses the AppUserManager class to retrieve an AppUser instance to represent the current user. I pass the AppUser object as the view model object in the GET version of the UserProps action method, and the POST method uses it to update the value of the new City property. Listing 15-3 shows the UserProps.cshtml view, which displays the City property value and contains a form to change it. 我添加了一个CurrentUser属性,它使用AppUserManager类接收了表示当前用户的AppUser实例。在GET版本的UserProps动作方法中,传递了这个AppUser对象作为视图模型。而在POST版的方法中用它更新了City属性的值。清单15-3显示了UserProps.cshtml视图,它显示了City属性的值,并包含一个修改它的表单。 Listing 15-3. The Contents of the UserProps.cshtml File in the Views/Home Folder 清单15-3. Views/Home文件夹中UserProps.cshtml文件的内容 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";}<div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr></table></div> @using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Caution Don’t start the application when you have created the view. In the sections that follow, I demonstrate how to preserve the contents of the database, and if you start the application now, the ASP.NET Identity users will be deleted. 警告:创建了视图之后不要启动应用程序。在以下小节中,将演示如何保留数据库的内容,如果现在启动应用程序,将会删除ASP.NET Identity的用户。 15.2.2 Preparing for Database Migration 15.2.2 准备数据库迁移 The default behavior for the Entity Framework Code First feature is to drop the tables in the database and re-create them whenever classes that drive the schema have changed. You saw this in Chapter 14 when I added support for roles: When the application was started, the database was reset, and the user accounts were lost. Entity Framework Code First特性的默认行为是,一旦修改了派生数据库架构的类,便会删除数据库中的数据表,并重新创建它们。在第14章可以看到这种情况,在我添加角色支持时:当重启应用程序后,数据库被重置,用户账号也丢失。 Don’t start the application yet, but if you were to do so, you would see a similar effect. Deleting data during development is usually not a problem, but doing so in a production setting is usually disastrous because it deletes all of the real user accounts and causes a panic while the backups are restored. In this section, I am going to demonstrate how to use the database migration feature, which updates a Code First schema in a less brutal manner and preserves the existing data it contains. 不要启动应用程序,但如果你这么做了,会看到类似的效果。在开发期间删除数据没什么问题,但如果在产品设置中这么做了,通常是灾难性的,因为它会删除所有真实的用户账号,而备份恢复是很痛苦的事。在本小节中,我打算演示如何使用数据库迁移特性,它能以比较温和的方式更新Code First的架构,并保留架构中的已有数据。 The first step is to issue the following command in the Visual Studio Package Manager Console: 第一个步骤是在Visual Studio的“Package Manager Console(包管理器控制台)”中发布以下命令: Enable-Migrations –EnableAutomaticMigrations This enables the database migration support and creates a Migrations folder in the Solution Explorer that contains a Configuration.cs class file, the contents of which are shown in Listing 15-4. 它启用了数据库的迁移支持,并在“Solution Explorer(解决方案资源管理器)”创建一个Migrations文件夹,其中含有一个Configuration.cs类文件,内容如清单15-4所示。 Listing 15-4. The Contents of the Configuration.cs File 清单15-4. Configuration.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity;using System.Data.Entity.Migrations;using System.Linq;internal sealed class Configuration: DbMigrationsConfiguration<Users.Infrastructure.AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(Users.Infrastructure.AppIdentityDbContext context) {// This method will be called after migrating to the latest version.// 此方法将在迁移到最新版本时调用// You can use the DbSet<T>.AddOrUpdate() helper extension method// to avoid creating duplicate seed data. E.g.// 例如,你可以使用DbSet<T>.AddOrUpdate()辅助器方法来避免创建重复的种子数据//// context.People.AddOrUpdate(// p => p.FullName,// new Person { FullName = "Andrew Peters" },// new Person { FullName = "Brice Lambson" },// new Person { FullName = "Rowan Miller" }// );//} }} Tip You might be wondering why you are entering a database migration command into the console used to manage NuGet packages. The answer is that the Package Manager Console is really PowerShell, which is a general-purpose tool that is mislabeled by Visual Studio. You can use the console to issue a wide range of helpful commands. See http://go.microsoft.com/fwlink/?LinkID=108518 for details. 提示:你可能会觉得奇怪,为什么要在管理NuGet包的控制台中输入数据库迁移的命令?答案是“Package Manager Console(包管理控制台)”是真正的PowerShell,这是Visual studio冒用的一个通用工具。你可以使用此控制台发送大量的有用命令,详见http://go.microsoft.com/fwlink/?LinkID=108518。 The class will be used to migrate existing content in the database to the new schema, and the Seed method will be called to provide an opportunity to update the existing database records. In Listing 15-5, you can see how I have used the Seed method to set a default value for the new City property I added to the AppUser class. (I have also updated the class file to reflect my usual coding style.) 这个类将用于把数据库中的现有内容迁移到新的数据库架构,Seed方法的调用为更新现有数据库记录提供了机会。在清单15-5中可以看到,我如何用Seed方法为新的City属性设置默认值,City是添加到AppUser类中自定义属性。(为了体现我一贯的编码风格,我对这个类文件也进行了更新。) Listing 15-5. Managing Existing Content in the Configuration.cs File 清单15-5. 在Configuration.cs文件中管理已有内容 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models;namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);}foreach (AppUser dbUser in userMgr.Users) {dbUser.City = Cities.PARIS;}context.SaveChanges();} }} You will notice that much of the code that I added to the Seed method is taken from the IdentityDbInit class, which I used to seed the database with an administration user in Chapter 14. This is because the new Configuration class added to support database migrations will replace the seeding function of the IdentityDbInit class, which I’ll update shortly. Aside from ensuring that there is an admin user, the statements in the Seed method that are important are the ones that set the initial value for the City property I added to the AppUser class, as follows: 你可能会注意到,添加到Seed方法中的许多代码取自于IdentityDbInit类,在第14章中我用这个类将管理用户植入了数据库。这是因为这个新添加的、用以支持数据库迁移的Configuration类,将代替IdentityDbInit类的种植功能,我很快便会更新这个类。除了要确保有admin用户之外,在Seed方法中的重要语句是那些为AppUser类的City属性设置初值的语句,如下所示: ...foreach (AppUser dbUser in userMgr.Users) { dbUser.City = Cities.PARIS;}context.SaveChanges();... You don’t have to set a default value for new properties—I just wanted to demonstrate that the Seed method in the Configuration class can be used to update the existing user records in the database. 你不一定要为新属性设置默认值——这里只是想演示Configuration类中的Seed方法,可以用它更新数据库中的已有用户记录。 Caution Be careful when setting values for properties in the Seed method for real projects because the values will be applied every time you change the schema, overriding any values that the user has set since the last schema update was performed. I set the value of the City property just to demonstrate that it can be done. 警告:在用于真实项目的Seed方法中为属性设置值时要小心,因为你每一次修改架构时,都会运用这些值,这会将自执行上一次架构更新之后,用户设置的任何数据覆盖掉。这里设置City属性的值只是为了演示它能够这么做。 Changing the Database Context Class 修改数据库上下文类 The reason that I added the seeding code to the Configuration class is that I need to change the IdentityDbInit class. At present, the IdentityDbInit class is derived from the descriptively named DropCreateDatabaseIfModelChanges<AppIdentityDbContext> class, which, as you might imagine, drops the entire database when the Code First classes change. Listing 15-6 shows the changes I made to the IdentityDbInit class to prevent it from affecting the database. 在Configuration类中添加种植代码的原因是我需要修改IdentityDbInit类。此时,IdentityDbInit类派生于描述性命名的DropCreateDatabaseIfModelChanges<AppIdentityDbContext> 类,和你相像的一样,它会在Code First类改变时删除整个数据库。清单15-6显示了我对IdentityDbInit类所做的修改,以防止它影响数据库。 Listing 15-6. Preventing Database Schema Changes in the AppIdentityDbContext.cs File 清单15-6. 在AppIdentityDbContext.cs文件是阻止数据库架构变化 using System.Data.Entity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Models;using Microsoft.AspNet.Identity; namespace Users.Infrastructure {public class AppIdentityDbContext : IdentityDbContext<AppUser> {public AppIdentityDbContext() : base("IdentityDb") { }static AppIdentityDbContext() {Database.SetInitializer<AppIdentityDbContext>(new IdentityDbInit());}public static AppIdentityDbContext Create() {return new AppIdentityDbContext();} } public class IdentityDbInit : NullDatabaseInitializer<AppIdentityDbContext> {} } I have removed the methods defined by the class and changed its base to NullDatabaseInitializer<AppIdentityDbContext> , which prevents the schema from being altered. 我删除了这个类中所定义的方法,并将它的基类改为NullDatabaseInitializer<AppIdentityDbContext> ,它可以防止架构修改。 15.2.3 Performing the Migration 15.2.3 执行迁移 All that remains is to generate and apply the migration. First, run the following command in the Package Manager Console: 剩下的事情只是生成并运用迁移了。首先,在“Package Manager Console(包管理器控制台)”中执行以下命令: Add-Migration CityProperty This creates a new migration called CityProperty (I like my migration names to reflect the changes I made). A class new file will be added to the Migrations folder, and its name reflects the time at which the command was run and the name of the migration. My file is called 201402262244036_CityProperty.cs, for example. The contents of this file contain the details of how Entity Framework will change the database during the migration, as shown in Listing 15-7. 这创建了一个名称为CityProperty的新迁移(我比较喜欢让迁移的名称反映出我所做的修改)。这会在文件夹中添加一个新的类文件,而且其命名会反映出该命令执行的时间以及迁移名称,例如,我的这个文件名称为201402262244036_CityProperty.cs。该文件的内容含有迁移期间Entity Framework修改数据库的细节,如清单15-7所示。 Listing 15-7. The Contents of the 201402262244036_CityProperty.cs File 清单15-7. 201402262244036_CityProperty.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity.Migrations; public partial class Init : DbMigration {public override void Up() {AddColumn("dbo.AspNetUsers", "City", c => c.Int(nullable: false));}public override void Down() {DropColumn("dbo.AspNetUsers", "City");} }} The Up method describes the changes that have to be made to the schema when the database is upgraded, which in this case means adding a City column to the AspNetUsers table, which is the one that is used to store user records in the ASP.NET Identity database. Up方法描述了在数据库升级时,需要对架构所做的修改,在这个例子中,意味着要在AspNetUsers数据表中添加City数据列,该数据表是ASP.NET Identity数据库用来存储用户记录的。 The final step is to perform the migration. Without starting the application, run the following command in the Package Manager Console: 最后一步是执行迁移。无需启动应用程序,只需在“Package Manager Console(包管理器控制台)”中运行以下命令即可: Update-Database –TargetMigration CityProperty The database schema will be modified, and the code in the Configuration.Seed method will be executed. The existing user accounts will have been preserved and enhanced with a City property (which I set to Paris in the Seed method). 这会修改数据库架构,并执行Configuration.Seed方法中的代码。已有用户账号会被保留,且增强了City属性(我在Seed方法中已将其设置为“Paris”)。 15.2.4 Testing the Migration 15.2.4 测试迁移 To test the effect of the migration, start the application, navigate to the /Home/UserProps URL, and authenticate as one of the Identity users (for example, as Alice with the password MySecret). Once authenticated, you will see the current value of the City property for the user and have the opportunity to change it, as shown in Figure 15-3. 为了测试迁移的效果,启动应用程序,导航到/Home/UserProps URL,并以Identity中的用户(例如Alice,口令MySecret)进行认证。一旦已被认证,便会看到该用户City属性的当前值,并可以对其进行修改,如图15-3所示。 Figure 15-3. Displaying and changing a custom user property 图15-3. 显示和个性自定义用户属性 15.2.5 Defining an Additional Property 15.2.5 定义附加属性 Now that database migrations are set up, I am going to define a further property just to demonstrate how subsequent changes are handled and to show a more useful (and less dangerous) example of using the Configuration.Seed method. Listing 15-8 shows how I added a Country property to the AppUser class. 现在,已经建立了数据库迁移,我打算再定义一个属性,这恰恰演示了如何处理持续不断的修改,也为了演示Configuration.Seed方法更有用(至少无害)的示例。清单15-8显示了我在AppUser类上添加了一个Country属性。 Listing 15-8. Adding Another Property in the AppUserModels.cs File 清单15-8. 在AppUserModels.cs文件中添加另一个属性 using System;using Microsoft.AspNet.Identity.EntityFramework; namespace Users.Models {public enum Cities {LONDON, PARIS, CHICAGO} public enum Countries {NONE, UK, FRANCE, USA}public class AppUser : IdentityUser {public Cities City { get; set; }public Countries Country { get; set; }public void SetCountryFromCity(Cities city) {switch (city) {case Cities.LONDON:Country = Countries.UK;break;case Cities.PARIS:Country = Countries.FRANCE;break;case Cities.CHICAGO:Country = Countries.USA;break;default:Country = Countries.NONE;break;} }} } I have added an enumeration to define the country names and a helper method that selects a country value based on the City property. Listing 15-9 shows the change I made to the Configuration class so that the Seed method sets the Country property based on the City, but only if the value of Country is NONE (which it will be for all users when the database is migrated because the Entity Framework sets enumeration columns to the first value). 我已经添加了一个枚举,它定义了国家名称。还添加了一个辅助器方法,它可以根据City属性选择一个国家。清单15-9显示了对Configuration类所做的修改,以使Seed方法根据City设置Country属性,但只当Country为NONE时才进行设置(在迁移数据库时,所有用户都是NONE,因为Entity Framework会将枚举列设置为枚举的第一个值)。 Listing 15-9. Modifying the Database Seed in the Configuration.cs File 清单15-9. 在Configuration.cs文件中修改数据库种子 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models; namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);} foreach (AppUser dbUser in userMgr.Users) {if (dbUser.Country == Countries.NONE) {dbUser.SetCountryFromCity(dbUser.City);} }context.SaveChanges();} }} This kind of seeding is more useful in a real project because it will set a value for the Country property only if one has not already been set—subsequent migrations won’t be affected, and user selections won’t be lost. 这种种植在实际项目中会更有用,因为它只会在Country属性未设置时,才会设置Country属性的值——后继的迁移不会受到影响,因此不会失去用户的选择。 1. Adding Application Support 1. 添加应用程序支持 There is no point defining additional user properties if they are not available in the application, so Listing 15-10 shows the change I made to the Views/Home/UserProps.cshtml file to display the value of the Country property. 应用程序中如果没有定义附加属性的地方,则附加属性就无法使用了,因此,清单15-10显示了我对Views/Home/UserProps.cshtml文件的修改,以显示Country属性的值。 Listing 15-10. Displaying an Additional Property in the UserProps.cshtml File 清单15-10. 在UserProps.cshtml文件中显示附加属性 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";} <div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr> <tr><th>Country</th><td>@Model.Country</td></tr></table></div>@using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Listing 15-11 shows the corresponding change I made to the Home controller to update the Country property when the City value changes. 为了在City值变化时能够更新Country属性,清单15-11显示了我对Home控制器所做的相应修改。 Listing 15-11. Setting Custom Properties in the HomeController.cs File 清单15-11. 在HomeController.cs文件中设置自定义属性 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models; namespace Users.Controllers {public class HomeController : Controller {// ...other action methods omitted for brevity...// ...出于简化,这里忽略了其他动作方法... [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;user.SetCountryFromCity(city);await UserManager.UpdateAsync(user);return View(user);}// ...properties omitted for brevity...// ...出于简化,这里忽略了一些属性...} } 2. Performing the Migration 2. 准备迁移 All that remains is to create and apply a new migration. Enter the following command into the Package Manager Console: 剩下的事情就是创建和运用新的迁移了。在“Package Manager Console(包管理器控制台)”中输入以下命令: Add-Migration CountryProperty This will generate another file in the Migrations folder that contains the instruction to add the Country column. To apply the migration, execute the following command: 这将在Migrations文件夹中生成另一个文件,它含有添加Country数据表列的指令。为了运用迁移,可执行以下命令: Update-Database –TargetMigration CountryProperty The migration will be performed, and the value of the Country property will be set based on the value of the existing City property for each user. You can check the new user property by starting the application and authenticating and navigating to the /Home/UserProps URL, as shown in Figure 15-4. 这将执行迁移,Country属性的值将根据每个用户当前的City属性进行设置。通过启动应用程序,认证并导航到/Home/UserProps URL,便可以查看新的用户属性,如图15-4所示。 Figure 15-4. Creating an additional user property 图15-4. 创建附加用户属性 Tip Although I am focused on the process of upgrading the database, you can also migrate back to a previous version by specifying an earlier migration. Use the –Force argument make changes that cause data loss, such as removing a column. 提示:虽然我们关注了升级数据库的过程,但你也可以回退到以前的版本,只需指定一个早期的迁移即可。使用-Force参数进行修改,会引起数据丢失,例如删除数据表列。 15.3 Working with Claims 15.3 使用声明(Claims) In older user-management systems, such as ASP.NET Membership, the application was assumed to be the authoritative source of all information about the user, essentially treating the application as a closed world and trusting the data that is contained within it. 在旧的用户管理系统中,例如ASP.NET Membership,应用程序被假设成是用户所有信息的权威来源,本质上将应用程序视为是一个封闭的世界,并且只信任其中所包含的数据。 This is such an ingrained approach to software development that it can be hard to recognize that’s what is happening, but you saw an example of the closed-world technique in Chapter 14 when I authenticated users against the credentials stored in the database and granted access based on the roles associated with those credentials. I did the same thing again in this chapter when I added properties to the user class. Every piece of information that I needed to manage user authentication and authorization came from within my application—and that is a perfectly satisfactory approach for many web applications, which is why I demonstrated these techniques in such depth. 这是软件开发的一种根深蒂固的方法,使人很难认识到这到底意味着什么,第14章你已看到了这种封闭世界技术的例子,根据存储在数据库中的凭据来认证用户,并根据与凭据关联在一起的角色来授权访问。本章前述在用户类上添加属性,也做了同样的事情。我管理用户认证与授权所需的每一个数据片段都来自于我的应用程序——而且这是许多Web应用程序都相当满意的一种方法,这也是我如此深入地演示这些技术的原因。 ASP.NET Identity also supports an alternative approach for dealing with users, which works well when the MVC framework application isn’t the sole source of information about users and which can be used to authorize users in more flexible and fluid ways than traditional roles allow. ASP.NET Identity还支持另一种处理用户的办法,当MVC框架的应用程序不是有关用户的唯一信息源时,这种办法会工作得很好,而且能够比传统的角色授权更为灵活且流畅的方式进行授权。 This alternative approach uses claims, and in this section I’ll describe how ASP.NET Identity supports claims-based authorization. Table 15-4 puts claims in context. 这种可选的办法使用了“Claims(声明)”,因此在本小节中,我将描述ASP.NET Identity如何支持“Claims-Based Authorization(基于声明的授权)”。表15-4描述了声明(Claims)的情形。 提示:“Claim”在英文字典中不完全是“声明”的意思,根据本文的描述,感觉把它说成“声明”也不一定合适,所以在之后的译文中基本都写成中英文并用的形式,即“声明(Claims)”。根据表15-4中的声明(Claims)的定义:声明(Claims)是关于用户的一些信息片段。一个用户的信息片段当然有很多,每一个信息片段就是一项声明(Claim),用户的所有信息片段合起来就是该用户的声明(Claims)。请读者注意该单词的单复数形式——译者注 Table 15-4. Putting Claims in Context 表15-4. 声明(Claims)的情形 Question 问题 Answer 答案 What is it? 什么是声明(Claims)? Claims are pieces of information about users that you can use to make authorization decisions. Claims can be obtained from external systems as well as from the local Identity database. 声明(Claims)是关于用户的一些信息片段,可以用它们做出授权决定。声明(Claims)可以从外部系统获取,也可以从本地的Identity数据库获取。 Why should I care? 为何要关心它? Claims can be used to flexibly authorize access to action methods. Unlike conventional roles, claims allow access to be driven by the information that describes the user. 声明(Claims)可以用来对动作方法进行灵活的授权访问。与传统的角色不同,声明(Claims)让访问能够由描述用户的信息进行驱动。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework, but it is integrated into the standard authorization features, such as the Authorize attribute. 这不是直接由MVC框架使用的特性,但它集成到了标准的授权特性之中,例如Authorize注解属性。 Tip you don’t have to use claims in your applications, and as Chapter 14 showed, ASP.NET Identity is perfectly happy providing an application with the authentication and authorization services without any need to understand claims at all. 提示:你在应用程序中不一定要使用声明(Claims),正如第14章所展示的那样,ASP.NET Identity能够为应用程序提供充分的认证与授权服务,而根本不需要理解声明(Claims)。 15.3.1 Understanding Claims 15.3.1 理解声明(Claims) A claim is a piece of information about the user, along with some information about where the information came from. The easiest way to unpack claims is through some practical demonstrations, without which any discussion becomes too abstract to be truly useful. To get started, I added a Claims controller to the example project, the definition of which you can see in Listing 15-12. 一项声明(Claim)是关于用户的一个信息片段(请注意这个英文单词的单复数形式——译者注),并伴有该片段出自何处的某种信息。揭开声明(Claims)含义最容易的方式是做一些实际演示,任何讨论都会过于抽象根本没有真正的用处。为此,我在示例项目中添加了一个Claims控制器,其定义如清单15-12所示。 Listing 15-12. The Contents of the ClaimsController.cs File 清单15-12. ClaimsController.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} }} } Tip You may feel a little lost as I define the code for this example. Don’t worry about the details for the moment—just stick with it until you see the output from the action method and view that I define. More than anything else, that will help put claims into perspective. 提示:你或许会对我为此例定义的代码感到有点失望。此刻对此细节不必着急——只要稍事忍耐,当看到该动作方法和视图的输出便会明白。尤为重要的是,这有助于洞察声明(Claims)。 You can get the claims associated with a user in different ways. One approach is to use the Claims property defined by the user class, but in this example, I have used the HttpContext.User.Identity property to demonstrate the way that ASP.NET Identity is integrated with the rest of the ASP.NET platform. As I explained in Chapter 13, the HttpContext.User.Identity property returns an implementation of the IIdentity interface, which is a ClaimsIdentity object when working using ASP.NET Identity. The ClaimsIdentity class is defined in the System.Security.Claims namespace, and Table 15-5 shows the members it defines that are relevant to this chapter. 可以通过不同的方式获得与用户相关联的声明(Claims)。方法之一就是使用由用户类定义的Claims属性,但在这个例子中,我使用了HttpContext.User.Identity属性,目的是演示ASP.NET Identity与ASP.NET平台集成的方式(请注意这句话所表示的含义:用户类的Claims属性属于ASP.NET Identity,而HttpContext.User.Identity属性则属于ASP.NET平台。由此可见,ASP.NET Identity已经融合到了ASP.NET平台之中——译者注)。正如第13章所解释的那样,HttpContext.User.Identity属性返回IIdentity的接口实现,当使用ASP.NET Identity时,该实现是一个ClaimsIdentity对象。ClaimsIdentity类是在System.Security.Claims命名空间中定义的,表15-5显示了它所定义的与本章有关的成员。 Table 15-5. The Members Defined by the ClaimsIdentity Class 表15-5. ClaimsIdentity类所定义的成员 Name 名称 Description 描述 Claims Returns an enumeration of Claim objects representing the claims for the user. 返回表示用户声明(Claims)的Claim对象枚举 AddClaim(claim) Adds a claim to the user identity. 给用户添加一个声明(Claim) AddClaims(claims) Adds an enumeration of Claim objects to the user identity. 给用户添加Claim对象的枚举。 HasClaim(predicate) Returns true if the user identity contains a claim that matches the specified predicate. See the “Applying Claims” section for an example predicate. 如果用户含有与指定谓词匹配的声明(Claim)时,返回true。参见“运用声明(Claims)”中的示例谓词 RemoveClaim(claim) Removes a claim from the user identity. 删除用户的声明(Claim)。 Other members are available, but the ones in the table are those that are used most often in web applications, for reason that will become obvious as I demonstrate how claims fit into the wider ASP.NET platform. 还有一些可用的其它成员,但表中的这些是在Web应用程序中最常用的,随着我演示如何将声明(Claims)融入更宽泛的ASP.NET平台,它们为什么最常用就很显然了。 In Listing 15-12, I cast the IIdentity implementation to the ClaimsIdentity type and pass the enumeration of Claim objects returned by the ClaimsIdentity.Claims property to the View method. A Claim object represents a single piece of data about the user, and the Claim class defines the properties shown in Table 15-6. 在清单15-12中,我将IIdentity实现转换成了ClaimsIdentity类型,并且给View方法传递了ClaimsIdentity.Claims属性所返回的Claim对象的枚举。Claim对象所示表示的是关于用户的一个单一的数据片段,Claim类定义的属性如表15-6所示。 Table 15-6. The Properties Defined by the Claim Class 表15-6. Claim类定义的属性 Name 名称 Description 描述 Issuer Returns the name of the system that provided the claim 返回提供声明(Claim)的系统名称 Subject Returns the ClaimsIdentity object for the user who the claim refers to 返回声明(Claim)所指用户的ClaimsIdentity对象 Type Returns the type of information that the claim represents 返回声明(Claim)所表示的信息类型 Value Returns the piece of information that the claim represents 返回声明(Claim)所表示的信息片段 Listing 15-13 shows the contents of the Index.cshtml file that I created in the Views/Claims folder and that is rendered by the Index action of the Claims controller. The view adds a row to a table for each claim about the user. 清单15-13显示了我在Views/Claims文件夹中创建的Index.cshtml文件的内容,它由Claims控制器中的Index动作方法进行渲染。该视图为用户的每项声明(Claim)添加了一个表格行。 Listing 15-13. The Contents of the Index.cshtml File in the Views/Claims Folder 清单15-13. Views/Claims文件夹中Index.cshtml文件的内容 @using System.Security.Claims@using Users.Infrastructure@model IEnumerable<Claim>@{ ViewBag.Title = "Claims"; }<div class="panel panel-primary"><div class="panel-heading">Claims</div><table class="table table-striped"><tr><th>Subject</th><th>Issuer</th><th>Type</th><th>Value</th></tr>@foreach (Claim claim in Model.OrderBy(x => x.Type)) {<tr><td>@claim.Subject.Name</td><td>@claim.Issuer</td><td>@Html.ClaimType(claim.Type)</td><td>@claim.Value</td></tr>}</table></div> The value of the Claim.Type property is a URI for a Microsoft schema, which isn’t especially useful. The popular schemas are used as the values for fields in the System.Security.Claims.ClaimTypes class, so to make the output from the Index.cshtml view easier to read, I added an HTML helper to the IdentityHelpers.cs file, as shown in Listing 15-14. It is this helper that I use in the Index.cshtml file to format the value of the Claim.Type property. Claim.Type属性的值是一个微软模式(Microsoft Schema)的URI(统一资源标识符),这是特别有用的。System.Security.Claims.ClaimTypes类中字段的值使用的是流行模式(Popular Schema),因此为了使Index.cshtml视图的输出更易于阅读,我在IdentityHelpers.cs文件中添加了一个HTML辅助器,如清单15-14所示。Index.cshtml文件正是使用这个辅助器格式化了Claim.Type属性的值。 Listing 15-14. Adding a Helper to the IdentityHelpers.cs File 清单15-14. 在IdentityHelpers.cs文件中添加辅助器 using System.Web;using System.Web.Mvc;using Microsoft.AspNet.Identity.Owin;using System;using System.Linq;using System.Reflection;using System.Security.Claims;namespace Users.Infrastructure {public static class IdentityHelpers {public static MvcHtmlString GetUserName(this HtmlHelper html, string id) {AppUserManager mgr= HttpContext.Current.GetOwinContext().GetUserManager<AppUserManager>();return new MvcHtmlString(mgr.FindByIdAsync(id).Result.UserName);} public static MvcHtmlString ClaimType(this HtmlHelper html, string claimType) {FieldInfo[] fields = typeof(ClaimTypes).GetFields();foreach (FieldInfo field in fields) {if (field.GetValue(null).ToString() == claimType) {return new MvcHtmlString(field.Name);} }return new MvcHtmlString(string.Format("{0}",claimType.Split('/', '.').Last()));} }} Note The helper method isn’t at all efficient because it reflects on the fields of the ClaimType class for each claim that is displayed, but it is sufficient for my purposes in this chapter. You won’t often need to display the claim type in real applications. 注:该辅助器并非十分有效,因为它只是针对每个要显示的声明(Claim)映射出ClaimType类的字段,但对我要的目的已经足够了。在实际项目中不会经常需要显示声明(Claim)的类型。 To see why I have created a controller that uses claims without really explaining what they are, start the application, authenticate as the user Alice (with the password MySecret), and request the /Claims/Index URL. Figure 15-5 shows the content that is generated. 为了弄明白我为何要先创建一个使用声明(Claims)的控制器,而没有真正解释声明(Claims)是什么的原因,可以启动应用程序,以用户Alice进行认证(其口令是MySecret),并请求/Claims/Index URL。图15-5显示了生成的内容。 Figure 15-5. The output from the Index action of the Claims controller 图15-5. Claims控制器中Index动作的输出 It can be hard to make out the detail in the figure, so I have reproduced the content in Table 15-7. 这可能还难以认识到此图的细节,为此我在表15-7中重列了其内容。 Table 15-7. The Data Shown in Figure 15-5 表15-7. 图15-5中显示的数据 Subject(科目) Issuer(发行者) Type(类型) Value(值) Alice LOCAL AUTHORITY SecurityStamp Unique ID Alice LOCAL AUTHORITY IdentityProvider ASP.NET Identity Alice LOCAL AUTHORITY Role Employees Alice LOCAL AUTHORITY Role Users Alice LOCAL AUTHORITY Name Alice Alice LOCAL AUTHORITY NameIdentifier Alice’s user ID The table shows the most important aspect of claims, which is that I have already been using them when I implemented the traditional authentication and authorization features in Chapter 14. You can see that some of the claims relate to user identity (the Name claim is Alice, and the NameIdentifier claim is Alice’s unique user ID in my ASP.NET Identity database). 此表展示了声明(Claims)最重要的方面,这些是我在第14章中实现传统的认证和授权特性时,一直在使用的信息。可以看出,有些声明(Claims)与用户标识有关(Name声明是Alice,NameIdentifier声明是Alice在ASP.NET Identity数据库中的唯一用户ID号)。 Other claims show membership of roles—there are two Role claims in the table, reflecting the fact that Alice is assigned to both the Users and Employees roles. There is also a claim about how Alice has been authenticated: The IdentityProvider is set to ASP.NET Identity. 其他声明(Claims)显示了角色成员——表中有两个Role声明(Claim),体现出Alice被赋予了Users和Employees两个角色这一事实。还有一个是Alice已被认证的声明(Claim):IdentityProvider被设置到了ASP.NET Identity。 The difference when this information is expressed as a set of claims is that you can determine where the data came from. The Issuer property for all the claims shown in the table is set to LOCAL AUTHORITY, which indicates that the user’s identity has been established by the application. 当这种信息被表示成一组声明(Claims)时的差别是,你能够确定这些数据是从哪里来的。表中所显示的所有声明的Issuer属性(发布者)都被设置到了LOACL AUTHORITY(本地授权),这说明该用户的标识是由应用程序建立的。 So, now that you have seen some example claims, I can more easily describe what a claim is. A claim is any piece of information about a user that is available to the application, including the user’s identity and role memberships. And, as you have seen, the information I have been defining about my users in earlier chapters is automatically made available as claims by ASP.NET Identity. 因此,现在你已经看到了一些声明(Claims)示例,我可以更容易地描述声明(Claim)是什么了。一项声明(Claim)是可用于应用程序中的有关用户的一个信息片段,包括用户的标识以及角色成员等。而且,正如你所看到的,我在前几章定义的关于用户的信息,被ASP.NET Identity自动地作为声明(Claims)了。 15.3.2 Creating and Using Claims 15.3.2 创建和使用声明(Claims) Claims are interesting for two reasons. The first reason is that an application can obtain claims from multiple sources, rather than just relying on a local database for information about the user. You will see a real example of this when I show you how to authenticate users through a third-party system in the “Using Third-Party Authentication” section, but for the moment I am going to add a class to the example project that simulates a system that provides claims information. Listing 15-15 shows the contents of the LocationClaimsProvider.cs file that I added to the Infrastructure folder. 声明(Claims)比较有意思的原因有两个。第一个原因是应用程序可以从多个来源获取声明(Claims),而不是只能依靠本地数据库关于用户的信息。你将会看到一个实际的示例,在“使用第三方认证”小节中,将演示如何通过第三方系统来认证用户。不过,此刻我只打算在示例项目中添加一个类,用以模拟一个提供声明(Claims)信息的系统。清单15-15显示了我添加到Infrastructure文件夹中LocationClaimsProvider.cs文件的内容。 Listing 15-15. The Contents of the LocationClaimsProvider.cs File 清单15-15. LocationClaimsProvider.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public static class LocationClaimsProvider {public static IEnumerable<Claim> GetClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.Name.ToLower() == "alice") {claims.Add(CreateClaim(ClaimTypes.PostalCode, "DC 20500"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "DC"));} else {claims.Add(CreateClaim(ClaimTypes.PostalCode, "NY 10036"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "NY"));}return claims;}private static Claim CreateClaim(string type, string value) {return new Claim(type, value, ClaimValueTypes.String, "RemoteClaims");} }} The GetClaims method takes a ClaimsIdentity argument and uses the Name property to create claims about the user’s ZIP code and state. This class allows me to simulate a system such as a central HR database, which would be the authoritative source of location information about staff, for example. GetClaims方法以ClaimsIdentity为参数,并使用Name属性创建了关于用户ZIP码(邮政编码)和州府的声明(Claims)。上述这个类使我能够模拟一个诸如中心化的HR数据库(人力资源数据库)之类的系统,它可能会成为全体职员的地点信息的权威数据源。 Claims are associated with the user’s identity during the authentication process, and Listing 15-16 shows the changes I made to the Login action method of the Account controller to call the LocationClaimsProvider class. 在认证过程期间,声明(Claims)是与用户标识关联在一起的,清单15-16显示了我对Account控制器中Login动作方法所做的修改,以便调用LocationClaimsProvider类。 Listing 15-16. Associating Claims with a User in the AccountController.cs File 清单15-16. AccountController.cs文件中用户用声明的关联 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... You can see the effect of the location claims by starting the application, authenticating as a user, and requesting the /Claim/Index URL. Figure 15-6 shows the claims for Alice. You may have to sign out and sign back in again to see the change. 为了看看这个地点声明(Claims)的效果,可以启动应用程序,以一个用户进行认证,并请求/Claim/Index URL。图15-6显示了Alice的声明(Claims)。你可能需要退出,然后再次登录才会看到发生的变化。 Figure 15-6. Defining additional claims for users 图15-6. 定义用户的附加声明 Obtaining claims from multiple locations means that the application doesn’t have to duplicate data that is held elsewhere and allows integration of data from external parties. The Claim.Issuer property tells you where a claim originated from, which helps you judge how accurate the data is likely to be and how much weight you should give the data in your application. Location data obtained from a central HR database is likely to be more accurate and trustworthy than data obtained from an external mailing list provider, for example. 从多个地点获取声明(Claims)意味着应用程序不必复制其他地方保持的数据,并且能够与外部的数据集成。Claim.Issuer属性(图15-6中的Issuer数据列——译者注)能够告诉你一个声明(Claim)的发源地,这有助于让你判断数据的精确程度,也有助于让你决定这类数据在应用程序中的权重。例如,从中心化的HR数据库获取的地点数据可能要比外部邮件列表提供器获取的数据更为精确和可信。 1. Applying Claims 1. 运用声明(Claims) The second reason that claims are interesting is that you can use them to manage user access to your application more flexibly than with standard roles. The problem with roles is that they are static, and once a user has been assigned to a role, the user remains a member until explicitly removed. This is, for example, how long-term employees of big corporations end up with incredible access to internal systems: They are assigned the roles they require for each new job they get, but the old roles are rarely removed. (The unexpectedly broad systems access sometimes becomes apparent during the investigation into how someone was able to ship the contents of the warehouse to their home address—true story.) 声明(Claims)有意思的第二个原因是,你可以用它们来管理用户对应用程序的访问,这要比标准的角色管理更为灵活。角色的问题在于它们是静态的,而且一旦用户已经被赋予了一个角色,该用户便是一个成员,直到明确地删除为止。例如,这意味着大公司的长期雇员,对内部系统的访问会十分惊人:他们每次在获得新工作时,都会赋予所需的角色,但旧角色很少被删除。(在调查某人为何能够将仓库里的东西发往他的家庭地址过程中发现,有时会出现异常宽泛的系统访问——真实的故事) Claims can be used to authorize users based directly on the information that is known about them, which ensures that the authorization changes when the data changes. The simplest way to do this is to generate Role claims based on user data that are then used by controllers to restrict access to action methods. Listing 15-17 shows the contents of the ClaimsRoles.cs file that I added to the Infrastructure. 声明(Claims)可以直接根据用户已知的信息对用户进行授权,这能够保证当数据发生变化时,授权也随之而变。此事最简单的做法是根据用户数据来生成Role声明(Claim),然后由控制器用来限制对动作方法的访问。清单15-17显示了我添加到Infrastructure中的ClaimsRoles.cs文件的内容。 Listing 15-17. The Contents of the ClaimsRoles.cs File 清单15-17. ClaimsRoles.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public class ClaimsRoles {public static IEnumerable<Claim> CreateRolesFromClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.HasClaim(x => x.Type == ClaimTypes.StateOrProvince&& x.Issuer == "RemoteClaims" && x.Value == "DC")&& user.HasClaim(x => x.Type == ClaimTypes.Role&& x.Value == "Employees")) {claims.Add(new Claim(ClaimTypes.Role, "DCStaff"));}return claims;} }} The gnarly looking CreateRolesFromClaims method uses lambda expressions to determine whether the user has a StateOrProvince claim from the RemoteClaims issuer with a value of DC and a Role claim with a value of Employees. If the user has both claims, then a Role claim is returned for the DCStaff role. Listing 15-18 shows how I call the CreateRolesFromClaims method from the Login action in the Account controller. CreateRolesFromClaims是一个粗糙的考察方法,它使用了Lambda表达式,以检查用户是否具有StateOrProvince声明(Claim),该声明来自于RemoteClaims发行者(Issuer),值为DC。也检查用户是否具有Role声明(Claim),其值为Employees。如果用户这两个声明都有,那么便返回一个DCStaff角色的Role声明。清单15-18显示了如何在Account控制器中的Login动作中调用CreateRolesFromClaims方法。 Listing 15-18. Generating Roles Based on Claims in the AccountController.cs File 清单15-18. 在AccountController.cs中根据声明生成角色 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(LocationClaimsProvider.GetClaims(ident)); ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... I can then restrict access to an action method based on membership of the DCStaff role. Listing 15-19 shows a new action method I added to the Claims controller to which I have applied the Authorize attribute. 然后我可以根据DCStaff角色的成员,来限制对一个动作方法的访问。清单15-19显示了在Claims控制器中添加的一个新的动作方法,在该方法上已经运用了Authorize注解属性。 Listing 15-19. Adding a New Action Method to the ClaimsController.cs File 清单15-19. 在ClaimsController.cs文件中添加一个新的动作方法 using System.Security.Claims;using System.Web;using System.Web.Mvc;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [Authorize(Roles="DCStaff")]public string OtherAction() {return "This is the protected action";} }} Users will be able to access OtherAction only if their claims grant them membership to the DCStaff role. Membership of this role is generated dynamically, so a change to the user’s employment status or location information will change their authorization level. 只要用户的声明(Claims)承认他们是DCStaff角色的成员,那么他们便能访问OtherAction动作。该角色的成员是动态生成的,因此,若是用户的雇用状态或地点信息发生变化,也会改变他们的授权等级。 提示:请读者从这个例子中吸取其中的思想精髓。对于读物的理解程度,仁者见仁,智者见智,能领悟多少,全凭各人,译者感觉这里的思想有无数的可能。举例说明:(1)可以根据用户的身份进行授权,比如学生在校时是“学生”,毕业后便是“校友”;(2)可以根据用户所处的部门进行授权,人事部用户属于人事团队,销售部用户属于销售团队,各团队有其自己的应用;(3)下一小节的示例是根据用户的地点授权。简言之:一方面用户的各种声明(Claim)都可以用来进行授权;另一方面用户的声明(Claim)又是可以自定义的。于是可能的运用就无法估计了。总之一句话,这种基于声明的授权(Claims-Based Authorization)有无限可能!要是没有我这里的提示,是否所有读者在此处都会有所体会?——译者注 15.3.3 Authorizing Access Using Claims 15.3.3 使用声明(Claims)授权访问 The previous example is an effective demonstration of how claims can be used to keep authorizations fresh and accurate, but it is a little indirect because I generate roles based on claims data and then enforce my authorization policy based on the membership of that role. A more direct and flexible approach is to enforce authorization directly by creating a custom authorization filter attribute. Listing 15-20 shows the contents of the ClaimsAccessAttribute.cs file, which I added to the Infrastructure folder and used to create such a filter. 前面的示例有效地演示了如何用声明(Claims)来保持新鲜和准确的授权,但有点不太直接,因为我要根据声明(Claims)数据来生成了角色,然后强制我的授权策略基于角色成员。一个更直接且灵活的办法是直接强制授权,其做法是创建一个自定义的授权过滤器注解属性。清单15-20演示了ClaimsAccessAttribute.cs文件的内容,我将它添加在Infrastructure文件夹中,并用它创建了这种过滤器。 Listing 15-20. The Contents of the ClaimsAccessAttribute.cs File 清单15-20. ClaimsAccessAttribute.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Infrastructure {public class ClaimsAccessAttribute : AuthorizeAttribute {public string Issuer { get; set; }public string ClaimType { get; set; }public string Value { get; set; }protected override bool AuthorizeCore(HttpContextBase context) {return context.User.Identity.IsAuthenticated&& context.User.Identity is ClaimsIdentity&& ((ClaimsIdentity)context.User.Identity).HasClaim(x =>x.Issuer == Issuer && x.Type == ClaimType && x.Value == Value);} }} The attribute I have defined is derived from the AuthorizeAttribute class, which makes it easy to create custom authorization policies in MVC framework applications by overriding the AuthorizeCore method. My implementation grants access if the user is authenticated, the IIdentity implementation is an instance of ClaimsIdentity, and the user has a claim with the issuer, type, and value matching the class properties. Listing 15-21 shows how I applied the attribute to the Claims controller to authorize access to the OtherAction method based on one of the location claims created by the LocationClaimsProvider class. 我所定义的这个注解属性派生于AuthorizeAttribute类,通过重写AuthorizeCore方法,很容易在MVC框架应用程序中创建自定义的授权策略。在这个实现中,若用户是已认证的、其IIdentity实现是一个ClaimsIdentity实例,而且该用户有一个带有issuer、type以及value的声明(Claim),它们与这个类的属性是匹配的,则该用户便是允许访问的。清单15-21显示了如何将这个注解属性运用于Claims控制器,以便根据LocationClaimsProvider类创建的地点声明(Claim),对OtherAction方法进行授权访问。 Listing 15-21. Performing Authorization on Claims in the ClaimsController.cs File 清单15-21. 在ClaimsController.cs文件中执行基于声明的授权 using System.Security.Claims;using System.Web;using System.Web.Mvc;using Users.Infrastructure;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [ClaimsAccess(Issuer="RemoteClaims", ClaimType=ClaimTypes.PostalCode,Value="DC 20500")]public string OtherAction() {return "This is the protected action";} }} My authorization filter ensures that only users whose location claims specify a ZIP code of DC 20500 can invoke the OtherAction method. 这个授权过滤器能够确保只有地点声明(Claim)的邮编为DC 20500的用户才能请求OtherAction方法。 15.4 Using Third-Party Authentication 15.4 使用第三方认证 One of the benefits of a claims-based system such as ASP.NET Identity is that any of the claims can come from an external system, even those that identify the user to the application. This means that other systems can authenticate users on behalf of the application, and ASP.NET Identity builds on this idea to make it simple and easy to add support for authenticating users through third parties such as Microsoft, Google, Facebook, and Twitter. 基于声明的系统,如ASP.NET Identity,的好处之一是任何声明都可以来自于外部系统,即使是将用户标识到应用程序的那些声明。这意味着其他系统可以代表应用程序来认证用户,而ASP.NET Identity就建立在这样的思想之上,使之能够简单而方便地添加第三方认证用户的支持,如微软、Google、Facebook、Twitter等。 There are some substantial benefits of using third-party authentication: Many users will already have an account, users can elect to use two-factor authentication, and you don’t have to manage user credentials in the application. In the sections that follow, I’ll show you how to set up and use third-party authentication for Google users, which Table 15-8 puts into context. 使用第三方认证有一些实际的好处:许多用户已经有了账号、用户可以选择使用双因子认证、你不必在应用程序中管理用户凭据等等。在以下小节中,我将演示如何为Google用户建立并使用第三方认证,表15-8描述了事情的情形。 Table 15-8. Putting Third-Party Authentication in Context 表15-8. 第三方认证情形 Question 问题 Answer 回答 What is it? 什么是第三方认证? Authenticating with third parties lets you take advantage of the popularity of companies such as Google and Facebook. 第三方认证使你能够利用流行公司,如Google和Facebook,的优势。 Why should I care? 为何要关心它? Users don’t like having to remember passwords for many different sites. Using a provider with large-scale adoption can make your application more appealing to users of the provider’s services. 用户不喜欢记住许多不同网站的口令。使用大范围适应的提供器可使你的应用程序更吸引有提供器服务的用户。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework. 这不是一个直接由MVC框架使用的特性。 Note The reason I have chosen to demonstrate Google authentication is that it is the only option that doesn’t require me to register my application with the authentication service. You can get details of the registration processes required at http://bit.ly/1cqLTrE. 提示:我选择演示Google认证的原因是,它是唯一不需要在其认证服务中注册我应用程序的公司。有关认证服务注册过程的细节,请参阅http://bit.ly/1cqLTrE。 15.4.1 Enabling Google Authentication 15.4.1 启用Google认证 ASP.NET Identity comes with built-in support for authenticating users through their Microsoft, Google, Facebook, and Twitter accounts as well more general support for any authentication service that supports OAuth. The first step is to add the NuGet package that includes the Google-specific additions for ASP.NET Identity. Enter the following command into the Package Manager Console: ASP.NET Identity带有通过Microsoft、Google、Facebook以及Twitter账号认证用户的内建支持,并且对于支持OAuth的认证服务具有更普遍的支持。第一个步骤是添加NuGet包,包中含有用于ASP.NET Identity的Google专用附件。请在“Package Manager Console(包管理器控制台)”中输入以下命令: Install-Package Microsoft.Owin.Security.Google -version 2.0.2 There are NuGet packages for each of the services that ASP.NET Identity supports, as described in Table 15-9. 对于ASP.NET Identity支持的每一种服务都有相应的NuGet包,如表15-9所示。 Table 15-9. The NuGet Authenticaton Packages 表15-9. NuGet认证包 Name 名称 Description 描述 Microsoft.Owin.Security.Google Authenticates users with Google accounts 用Google账号认证用户 Microsoft.Owin.Security.Facebook Authenticates users with Facebook accounts 用Facebook账号认证用户 Microsoft.Owin.Security.Twitter Authenticates users with Twitter accounts 用Twitter账号认证用户 Microsoft.Owin.Security.MicrosoftAccount Authenticates users with Microsoft accounts 用Microsoft账号认证用户 Microsoft.Owin.Security.OAuth Authenticates users against any OAuth 2.0 service 根据任一OAuth 2.0服务认证用户 Once the package is installed, I enable support for the authentication service in the OWIN startup class, which is defined in the App_Start/IdentityConfig.cs file in the example project. Listing 15-22 shows the change that I have made. 一旦安装了这个包,便可以在OWIN启动类中启用此项认证服务的支持,启动类的定义在示例项目的App_Start/IdentityConfig.cs文件中。清单15-22显示了所做的修改。 Listing 15-22. Enabling Google Authentication in the IdentityConfig.cs File 清单15-22. 在IdentityConfig.cs文件中启用Google认证 using Microsoft.AspNet.Identity;using Microsoft.Owin;using Microsoft.Owin.Security.Cookies;using Owin;using Users.Infrastructure;using Microsoft.Owin.Security.Google;namespace Users {public class IdentityConfig {public void Configuration(IAppBuilder app) {app.CreatePerOwinContext<AppIdentityDbContext>(AppIdentityDbContext.Create);app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions {AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,LoginPath = new PathString("/Account/Login"),}); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);app.UseGoogleAuthentication();} }} Each of the packages that I listed in Table 15-9 contains an extension method that enables the corresponding service. The extension method for the Google service is called UseGoogleAuthentication, and it is called on the IAppBuilder implementation that is passed to the Configuration method. 表15-9所列的每个包都含有启用相应服务的扩展方法。用于Google服务的扩展方法名称为UseGoogleAuthentication,它通过传递给Configuration方法的IAppBuilder实现进行调用。 Next I added a button to the Views/Account/Login.cshtml file, which allows users to log in via Google. You can see the change in Listing 15-23. 下一步骤是在Views/Account/Login.cshtml文件中添加一个按钮,让用户能够通过Google进行登录。所做的修改如清单15-23所示。 Listing 15-23. Adding a Google Login Button to the Login.cshtml File 清单15-23. 在Login.cshtml文件中添加Google登录按钮 @model Users.Models.LoginModel@{ ViewBag.Title = "Login";}<h2>Log In</h2> @Html.ValidationSummary()@using (Html.BeginForm()) {@Html.AntiForgeryToken();<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><div class="form-group"><label>Name</label>@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })</div><div class="form-group"><label>Password</label>@Html.PasswordFor(x => x.Password, new { @class = "form-control" })</div><button class="btn btn-primary" type="submit">Log In</button>}@using (Html.BeginForm("GoogleLogin", "Account")) {<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><button class="btn btn-primary" type="submit">Log In via Google</button>} The new button submits a form that targets the GoogleLogin action on the Account controller. You can see this method—and the other changes I made the controller—in Listing 15-24. 新按钮递交一个表单,目标是Account控制器中的GoogleLogin动作。可从清单15-24中看到该方法,以及在控制器中所做的其他修改。 Listing 15-24. Adding Support for Google Authentication to the AccountController.cs File 清单15-24. 在AccountController.cs文件中添加Google认证支持 using System.Threading.Tasks;using System.Web.Mvc;using Users.Models;using Microsoft.Owin.Security;using System.Security.Claims;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Infrastructure;using System.Web; namespace Users.Controllers {[Authorize]public class AccountController : Controller {[AllowAnonymous]public ActionResult Login(string returnUrl) {if (HttpContext.User.Identity.IsAuthenticated) {return View("Error", new string[] { "Access Denied" });}ViewBag.returnUrl = returnUrl;return View();}[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident)); AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);} [HttpPost][AllowAnonymous]public ActionResult GoogleLogin(string returnUrl) {var properties = new AuthenticationProperties {RedirectUri = Url.Action("GoogleLoginCallback",new { returnUrl = returnUrl})};HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();}[AllowAnonymous]public async Task<ActionResult> GoogleLoginCallback(string returnUrl) {ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();AppUser user = await UserManager.FindAsync(loginInfo.Login);if (user == null) {user = new AppUser {Email = loginInfo.Email,UserName = loginInfo.DefaultUserName,City = Cities.LONDON, Country = Countries.UK};IdentityResult result = await UserManager.CreateAsync(user);if (!result.Succeeded) {return View("Error", result.Errors);} else {result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);if (!result.Succeeded) {return View("Error", result.Errors);} }}ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false }, ident);return Redirect(returnUrl ?? "/");}[Authorize]public ActionResult Logout() {AuthManager.SignOut();return RedirectToAction("Index", "Home");}private IAuthenticationManager AuthManager {get {return HttpContext.GetOwinContext().Authentication;} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } The GoogleLogin method creates an instance of the AuthenticationProperties class and sets the RedirectUri property to a URL that targets the GoogleLoginCallback action in the same controller. The next part is a magic phrase that causes ASP.NET Identity to respond to an unauthorized error by redirecting the user to the Google authentication page, rather than the one defined by the application: GoogleLogin方法创建了AuthenticationProperties类的一个实例,并为RedirectUri属性设置了一个URL,其目标为同一控制器中的GoogleLoginCallback动作。下一个部分是一个神奇阶段,通过将用户重定向到Google认证页面,而不是应用程序所定义的认证页面,让ASP.NET Identity对未授权的错误进行响应: ...HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();... This means that when the user clicks the Log In via Google button, their browser is redirected to the Google authentication service and then redirected back to the GoogleLoginCallback action method once they are authenticated. 这意味着,当用户通过点击Google按钮进行登录时,浏览器被重定向到Google的认证服务,一旦在那里认证之后,便被重定向回GoogleLoginCallback动作方法。 I get details of the external login by calling the GetExternalLoginInfoAsync of the IAuthenticationManager implementation, like this: 我通过调用IAuthenticationManager实现的GetExternalLoginInfoAsync方法,我获得了外部登录的细节,如下所示: ...ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();... The ExternalLoginInfo class defines the properties shown in Table 15-10. ExternalLoginInfo类定义的属性如表15-10所示: Table 15-10. The Properties Defined by the ExternalLoginInfo Class 表15-10. ExternalLoginInfo类所定义的属性 Name 名称 Description 描述 DefaultUserName Returns the username 返回用户名 Email Returns the e-mail address 返回E-mail地址 ExternalIdentity Returns a ClaimsIdentity that identities the user 返回标识该用户的ClaimsIdentity Login Returns a UserLoginInfo that describes the external login 返回描述外部登录的UserLoginInfo I use the FindAsync method defined by the user manager class to locate the user based on the value of the ExternalLoginInfo.Login property, which returns an AppUser object if the user has been authenticated with the application before: 我使用了由用户管理器类所定义的FindAsync方法,以便根据ExternalLoginInfo.Login属性的值对用户进行定位,如果用户之前在应用程序中已经认证,该属性会返回一个AppUser对象: ...AppUser user = await UserManager.FindAsync(loginInfo.Login);... If the FindAsync method doesn’t return an AppUser object, then I know that this is the first time that this user has logged into the application, so I create a new AppUser object, populate it with values, and save it to the database. I also save details of how the user logged in so that I can find them next time: 如果FindAsync方法返回的不是AppUser对象,那么我便知道这是用户首次登录应用程序,于是便创建了一个新的AppUser对象,填充该对象的值,并将其保存到数据库。我还保存了用户如何登录的细节,以便下次能够找到他们: ...result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);... All that remains is to generate an identity the user, copy the claims provided by Google, and create an authentication cookie so that the application knows the user has been authenticated: 剩下的事情只是生成该用户的标识了,拷贝Google提供的声明(Claims),并创建一个认证Cookie,以使应用程序知道此用户已认证: ...ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);... 15.4.2 Testing Google Authentication 15.4.2 测试Google认证 There is one further change that I need to make before I can test Google authentication: I need to change the account verification I set up in Chapter 13 because it prevents accounts from being created with e-mail addresses that are not within the example.com domain. Listing 15-25 shows how I removed the verification from the AppUserManager class. 在测试Google认证之前还需要一处修改:需要修改第13章所建立的账号验证,因为它不允许example.com域之外的E-mail地址创建账号。清单15-25显示了如何在AppUserManager类中删除这种验证。 Listing 15-25. Disabling Account Validation in the AppUserManager.cs File 清单15-25. 在AppUserManager.cs文件中取消账号验证 using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Microsoft.AspNet.Identity.Owin;using Microsoft.Owin;using Users.Models; namespace Users.Infrastructure {public class AppUserManager : UserManager<AppUser> {public AppUserManager(IUserStore<AppUser> store): base(store) {}public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options,IOwinContext context) {AppIdentityDbContext db = context.Get<AppIdentityDbContext>();AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db)); manager.PasswordValidator = new CustomPasswordValidator {RequiredLength = 6,RequireNonLetterOrDigit = false,RequireDigit = false,RequireLowercase = true,RequireUppercase = true}; //manager.UserValidator = new CustomUserValidator(manager) {// AllowOnlyAlphanumericUserNames = true,// RequireUniqueEmail = true//};return manager;} }} Tip you can use validation for externally authenticated accounts, but I am just going to disable the feature for simplicity. 提示:也可以使用外部已认证账号的验证,但这里出于简化,取消了这一特性。 To test authentication, start the application, click the Log In via Google button, and provide the credentials for a valid Google account. When you have completed the authentication process, your browser will be redirected back to the application. If you navigate to the /Claims/Index URL, you will be able to see how claims from the Google system have been added to the user’s identity, as shown in Figure 15-7. 为了测试认证,启动应用程序,通过点击“Log In via Google(通过Google登录)”按钮,并提供有效的Google账号凭据。当你完成了认证过程时,浏览器将被重定向回应用程序。如果导航到/Claims/Index URL,便能够看到来自Google系统的声明(Claims),已被添加到用户的标识中了,如图15-7所示。 Figure 15-7. Claims from Google 图15-7. 来自Google的声明(Claims) 15.5 Summary 15.5 小结 In this chapter, I showed you some of the advanced features that ASP.NET Identity supports. I demonstrated the use of custom user properties and how to use database migrations to preserve data when you upgrade the schema to support them. I explained how claims work and how they can be used to create more flexible ways of authorizing users. I finished the chapter by showing you how to authenticate users via Google, which builds on the ideas behind the use of claims. 本章向你演示了ASP.NET Identity所支持的一些高级特性。演示了自定义用户属性的使用,还演示了在升级数据架构时,如何使用数据库迁移保护数据。我解释了声明(Claims)的工作机制,以及如何将它们用于创建更灵活的用户授权方式。最后演示了如何通过Google进行认证结束了本章,这是建立在使用声明(Claims)的思想基础之上的。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gz19871113/article/details/108591802。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-28 08:49:21
283
转载
转载文章
...功能。它能够添加到 Java 源代码的语法元数据。类、方法、变量、参数、包都可以被注解,可用来将信息元数据与程序元素进行关联。目前很多开源库都使用到了注解,最熟悉的ButtonKnife中的@ViewInject(R.id.x)就可以替代findViewId,不懂这一块技术的同学第一眼看上去肯定会一脸懵逼,下面会手把手带大家写出ButtonKnife的注解使用。使用注解可以简化代码,提高开发效率。本文简单介绍下注解的使用,并对几个 Android 开源库的注解使用原理进行简析。 1、作用 标记,用于告诉编译器一些信息 ; 编译时动态处理,如动态生成代码 ; 运行时动态处理,如得到注解信息。 2、分类 标准 Annotation, 包括 Override, Deprecated, SuppressWarnings。也都是Java自带的几个 Annotation,上面三个分别表示重写函数,不鼓励使用(有更好方式、使用有风险或已不在维护),忽略某项 Warning; 元 Annotation ,@Retention, @Target, @Inherited, @Documented。元 Annotation 是指用来定义 Annotation 的 Annotation,在后面 Annotation 自定义部分会详细介绍含义; 自定义 Annotation , 表示自己根据需要定义的 Annotation,定义时需要用到上面的元 Annotation 这里只是一种分类而已,也可以根据作用域分为源码时、编译时、运行时 Annotation。通过 @interface 定义,注解名即为自定义注解名。 一、自定义注解 例如,注解@MethodInfo: @Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@Inheritedpublic @interface MethodInfo {String author() default "annotation@gmail.com";String date();int version() default 1;} 使用到了元Annotation: @Documented 是否会保存到 Javadoc 文档中 ; @Retention 保留时间,可选值 SOURCE(源码时),CLASS(编译时),RUNTIME(运行时),默认为 CLASS,值为 SOURCE 大都为 Mark Annotation,这类 Annotation 大都用来校验,比如 Override, Deprecated, SuppressWarnings ; @Target 用来指定修饰的元素,如 CONSTRUCTOR:用于描述构造器、FIELD:用于描述域、LOCAL_VARIABLE:用于描述局部变量、METHOD:用于描述方法、PACKAGE:用于描述包、PARAMETER:用于描述参数、TYPE:用于描述类、接口(包括注解类型) 或enum声明。 @Inherited 是否可以被继承,默认为 false。 注解的参数名为注解类的方法名,且: 所有方法没有方法体,没有参数没有修饰符,实际只允许 public & abstract 修饰符,默认为 public ,不允许抛异常; 方法返回值只能是基本类型,String, Class, annotation, enumeration 或者是他们的一维数组; 若只有一个默认属性,可直接用 value() 函数。一个属性都没有表示该 Annotation 为 Mark Annotation。 public class App {@MethodInfo(author = “annotation.cn+android@gmail.com”,date = "2011/01/11",version = 2)public String getAppName() {return "appname";} } 调用自定义MethodInfo 的示例,这里注解的作用实际是给方法添加相关信息: author、date、version 。 二、实战注解Butter Knife 首先,先定义一个ViewInject注解。 public @interface ViewInject { int value() default -1;} 紧接着,为刚自定义注解添加元注解。 @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface ViewInject {int value() default -1;} 再定义一个注解LayoutInject @Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface LayoutInject {int value() default -1;} 定义一个基础的Activity。 package cn.wsy.myretrofit.annotation;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.util.Log;import java.lang.reflect.Field;public class InjectActivity extends AppCompatActivity {private int mLayoutId = -1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);displayInjectLayout();displayInjectView();}/ 解析注解view id/private void displayInjectView() {if (mLayoutId <=0){return ;}Class<?> clazz = this.getClass();Field[] fields = clazz.getDeclaredFields();//获得声明的成员变量for (Field field : fields) {//判断是否有注解try {if (field.getAnnotations() != null) {if (field.isAnnotationPresent(ViewInject.class)) {//如果属于这个注解//为这个控件设置属性field.setAccessible(true);//允许修改反射属性ViewInject inject = field.getAnnotation(ViewInject.class);field.set(this, this.findViewById(inject.value()));} }} catch (Exception e) {Log.e("wusy", "not found view id!");} }}/ 注解布局Layout id/private void displayInjectLayout() {Class<?> clazz = this.getClass();if (clazz.getAnnotations() != null){if (clazz.isAnnotationPresent(LayouyInject.class)){LayouyInject inject = clazz.getAnnotation(LayouyInject.class);mLayoutId = inject.value();setContentView(mLayoutId);} }} } 首先,这里是根据映射实现设置控件的注解,java中使用反射的机制效率性能并不高。这里只是举例子实现注解。ButterKnife官方申明不是通过反射机制,因此效率会高点。 package cn.wsy.myretrofit;import android.os.Bundle;import android.widget.TextView;import cn.wsy.myretrofit.annotation.InjectActivity;import cn.wsy.myretrofit.annotation.LayouyInject;import cn.wsy.myretrofit.annotation.ViewInject;@LayoutInject(R.layout.activity_main)public class MainActivity extends InjectActivity {@ViewInject(R.id.textview)private TextView textView;@ViewInject(R.id.textview1)private TextView textview1;@ViewInject(R.id.textview2)private TextView textview2;@ViewInject(R.id.textview3)private TextView textview3;@ViewInject(R.id.textview4)private TextView textview4;@ViewInject(R.id.textview5)private TextView textview5;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//设置属性textView.setText("OK");textview1.setText("OK1");textview2.setText("OK2");textview3.setText("OK3");textview4.setText("OK4");textview5.setText("OK5");} } 上面直接继承InjectActivity即可,文章上面也有说过:LayouyInject为什么作用域是TYPE,首先在加载view的时候,肯定是优先加载布局啊,ButterKnife也不例外。因此选择作用域在描述类,并且存在运行时。 二、解析Annotation原理 1、运行时 Annotation 解析 (1) 运行时 Annotation 指 @Retention 为 RUNTIME 的 Annotation,可手动调用下面常用 API 解析 method.getAnnotation(AnnotationName.class);method.getAnnotations();method.isAnnotationPresent(AnnotationName.class); 其他 @Target 如 Field,Class 方法类似 。 getAnnotation(AnnotationName.class) 表示得到该 Target 某个 Annotation 的信息,一个 Target 可以被多个 Annotation 修饰; getAnnotations() 则表示得到该 Target 所有 Annotation ; isAnnotationPresent(AnnotationName.class) 表示该 Target 是否被某个 Annotation 修饰; (2) 解析示例如下: public static void main(String[] args) {try {Class cls = Class.forName("cn.trinea.java.test.annotation.App");for (Method method : cls.getMethods()) {MethodInfo methodInfo = method.getAnnotation(MethodInfo.class);if (methodInfo != null) {System.out.println("method name:" + method.getName());System.out.println("method author:" + methodInfo.author());System.out.println("method version:" + methodInfo.version());System.out.println("method date:" + methodInfo.date());} }} catch (ClassNotFoundException e) {e.printStackTrace();} } 以之前自定义的 MethodInfo 为例,利用 Target(这里是 Method)getAnnotation 函数得到 Annotation 信息,然后就可以调用 Annotation 的方法得到响应属性值 。 2、编译时 Annotation 解析 (1) 编译时 Annotation 指 @Retention 为 CLASS 的 Annotation,甴 apt(Annotation Processing Tool) 解析自动解析。 使用方法: 自定义类集成自 AbstractProcessor; 重写其中的 process 函数 这块很多同学不理解,实际是 apt(Annotation Processing Tool) 在编译时自动查找所有继承自 AbstractProcessor 的类,然后调用他们的 process 方法去处理。 (2) 假设之前自定义的 MethodInfo 的 @Retention 为 CLASS,解析示例如下: @SupportedAnnotationTypes({ "cn.trinea.java.test.annotation.MethodInfo" })public class MethodInfoProcessor extends AbstractProcessor {@Overridepublic boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {HashMap<String, String> map = new HashMap<String, String>();for (TypeElement te : annotations) {for (Element element : env.getElementsAnnotatedWith(te)) {MethodInfo methodInfo = element.getAnnotation(MethodInfo.class);map.put(element.getEnclosingElement().toString(), methodInfo.author());} }return false;} } SupportedAnnotationTypes 表示这个 Processor 要处理的 Annotation 名字。 process 函数中参数 annotations 表示待处理的 Annotations,参数 env 表示当前或是之前的运行环境 process 函数返回值表示这组 annotations 是否被这个 Processor 接受,如果接受后续子的 rocessor 不会再对这个 Annotations 进行处理 三、几个 Android 开源库 Annotation 原理简析 1、Retrofit (1) 调用 @GET("/users/{username}")User getUser(@Path("username") String username); (2) 定义 @Documented@Target(METHOD)@Retention(RUNTIME)@RestMethod("GET")public @interface GET {String value();} 从定义可看出 Retrofit 的 Get Annotation 是运行时 Annotation,并且只能用于修饰 Method (3) 原理 private void parseMethodAnnotations() {for (Annotation methodAnnotation : method.getAnnotations()) {Class<? extends Annotation> annotationType = methodAnnotation.annotationType();RestMethod methodInfo = null;for (Annotation innerAnnotation : annotationType.getAnnotations()) {if (RestMethod.class == innerAnnotation.annotationType()) {methodInfo = (RestMethod) innerAnnotation;break;} }……} } RestMethodInfo.java 的 parseMethodAnnotations 方法如上,会检查每个方法的每个 Annotation, 看是否被 RestMethod 这个 Annotation 修饰的 Annotation 修饰,这个有点绕,就是是否被 GET、DELETE、POST、PUT、HEAD、PATCH 这些 Annotation 修饰,然后得到 Annotation 信息,在对接口进行动态代理时会掉用到这些 Annotation 信息从而完成调用。 因为 Retrofit 原理设计到动态代理,这里只介绍 Annotation。 2、Butter Knife (1) 调用 @InjectView(R.id.user) EditText username; (2) 定义 @Retention(CLASS) @Target(FIELD)public @interface InjectView {int value();} 可看出 Butter Knife 的 InjectView Annotation 是编译时 Annotation,并且只能用于修饰属性 (3) 原理 @Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {Map<TypeElement, ViewInjector> targetClassMap = findAndParseTargets(env);for (Map.Entry<TypeElement, ViewInjector> entry : targetClassMap.entrySet()) {TypeElement typeElement = entry.getKey();ViewInjector viewInjector = entry.getValue();try {JavaFileObject jfo = filer.createSourceFile(viewInjector.getFqcn(), typeElement);Writer writer = jfo.openWriter();writer.write(viewInjector.brewJava());writer.flush();writer.close();} catch (IOException e) {error(typeElement, "Unable to write injector for type %s: %s", typeElement, e.getMessage());} }return true;} ButterKnifeProcessor.java 的 process 方法如上,编译时,在此方法中过滤 InjectView 这个 Annotation 到 targetClassMap 后,会根据 targetClassMap 中元素生成不同的 class 文件到最终的 APK 中,然后在运行时调用 ButterKnife.inject(x) 函数时会到之前编译时生成的类中去找。 3、ActiveAndroid (1) 调用 @Column(name = “Name") public String name; (2) 定义 @Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface Column {……} 可看出 ActiveAndroid 的 Column Annotation 是运行时 Annotation,并且只能用于修饰属性 (3) 原理 Field idField = getIdField(type);mColumnNames.put(idField, mIdName);List<Field> fields = new LinkedList<Field>(ReflectionUtils.getDeclaredColumnFields(type));Collections.reverse(fields);for (Field field : fields) {if (field.isAnnotationPresent(Column.class)) {final Column columnAnnotation = field.getAnnotation(Column.class);String columnName = columnAnnotation.name();if (TextUtils.isEmpty(columnName)) {columnName = field.getName();}mColumnNames.put(field, columnName);} } TableInfo.java 的构造函数如上,运行时,得到所有行信息并存储起来用来构件表信息。 ———————————————————————— 最后一个问题,看看这段代码最后运行结果: public class Person {private int id;private String name;public Person(int id, String name) {this.id = id;this.name = name;}public boolean equals(Person person) {return person.id == id;}public int hashCode() {return id;}public static void main(String[] args) {Set<Person> set = new HashSet<Person>();for (int i = 0; i < 10; i++) {set.add(new Person(i, "Jim"));}System.out.println(set.size());} } 答案:示例代码运行结果应该是 10 而不是 1,这个示例代码程序实际想说明的是标记型注解 Override 的作用,为 equals 方法加上 Override 注解就知道 equals 方法的重载是错误的,参数不对。 本篇文章为转载内容。原文链接:https://blog.csdn.net/csdn_aiyang/article/details/81564408。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-03-28 22:30:35
104
转载
转载文章
...用于在线播放视频,该接口在课程管理服务中开发,供学习服务进行远程调用。 在学习服务中远程调用 课程计划媒资信息查询接口,获取该课程计划的视频播放的 m3u8 url地址,并返回给前端,前端使用该 url 进行视频的在线播放。 在线学习完整的测试流程:媒资信息的上传、选择、发布到前端门户、搜索门户测试,在线学习的播放视频。 目录 内容会比较多,小伙伴门可以根据目录进行按需查阅。 文章目录 😎 知识点概览 目录 一、学习页面:查询课程计划 0x01 需求分析 0x02 Api接口 0x03 服务端开发 Controller Service 测试 0x04 前端开发 配置NGINX虚拟主机 前端 API 方法 前端 API 方法调用 测试 二、学习页面:获取视频播放地址 0x01 需求分析 0x02 课程发布:储存媒资信息 需求分析 数据模型 Dao Service 测试 0x03 Logstash:扫描课程计划媒资 创建索引 创建模板文件 配置 mysql.conf 启动 logstash.bat Logstash多实例运行 0x04 搜素服务:查询课程媒资接口 需求分析 Api接口定义 Service Controller 测试 三、在线学习:接口开发 0x01 需求分析 0x02 搭建开发环境 0x03 Api接口 0x04 服务端开发 需求分析 搜索服务注册Eureka 搜索服务客户端 自定义错误代码 Service Controller 测试 0x05 前端开发 需求分析 api方法 配置代理 视频播放页面 简单的测试 完整的测试 1、上传文件 一些问题 ~~方案1:删除本地分块文件重新尝试上传~~ 方案2:检查前端提交的MD5值是否正确 2、为课程计划选择媒资信息 3、前端门户测试 四、待完善的一些功能 😁 认识作者 一、学习页面:查询课程计划 0x01 需求分析 到目前为止,我们已可以编辑课程计划信息并上传课程视频,下一步我们要实现在线学习页面动态读取章节对应的视频并进行播放。在线学习页面所需要的信息有两类: 课程计划信息 课程学习信息(视频地址、学习进度等) 如下图: 在线学习集成媒资管理的需求如下: 1、在线学习页面显示课程计划 2、点击课程计划播放该课程计划对应的视频 本章节实现学习页面动态显示课程计划,进入不同课程的学习页面右侧动态显示当前课程的课程计划。 0x02 Api接口 课程计划信息从哪里获取? 在课程发布完成后会自动发布到一个 course_pub 的表中,logstash 会自动将课程发布后的信息自动采集到 ES 索引库中,这些信息也包含课程计划信息。 所以考虑性能要求,课程发布后对课程的查询统一从 ES 索引库中查询。 前端通过请求 搜索服务 获取课程信息,需要单独在 搜索服务 中定义课程信息查询接口。 本接口接收课程id,查询课程所有信息返回给前端。 我们在搜素服务 API 下添加以下方法 @ApiOperation("根据id搜索课程发布信息")public Map<String,CoursePub> getdetail(String id); 返回的课程信息为 json 结构:key 为课程id,value 为课程内容。 0x03 服务端开发 在搜索服务中开发查询课程信息接口。 Controller 在搜素服务下添加以下方法 / 根据id搜索课程发布信息 @param id 课程id @return JSON数据/@Override@GetMapping("/getdetail/{id}")public Map<String, CoursePub> getdetail(@PathVariable("id")String id) {return esCourseService.getdetail(id);} Service / 根据id搜索课程发布信息 @param id 课程id @return JSON数据/public Map<String, CoursePub> getdetail(String id) {//设置索引SearchRequest searchRequest = new SearchRequest(es_index);//设置类型searchRequest.types(es_type);//创建搜索源对象SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//设置查询条件,根据id进行查询searchSourceBuilder.query(QueryBuilders.termQuery("id",id));//这里不使用source的原字段过滤,查询所有字段// searchSourceBuilder.fetchSource(new String[]{"name", "grade", "charge","pic"}, newString[]{});//设置搜索源对象searchRequest.source(searchSourceBuilder);//执行搜索SearchResponse searchResponse = null;try {searchResponse = restHighLevelClient.search(searchRequest);} catch (IOException e) {e.printStackTrace();}//获取搜索结果SearchHits hits = searchResponse.getHits();SearchHit[] searchHits = hits.getHits(); //获取最优结果Map<String,CoursePub> map = new HashMap<>();for (SearchHit hit: searchHits) {//从搜索结果中取值并添加到coursePub对象Map<String, Object> sourceAsMap = hit.getSourceAsMap();String courseId = (String) sourceAsMap.get("id");String name = (String) sourceAsMap.get("name");String grade = (String) sourceAsMap.get("grade");String charge = (String) sourceAsMap.get("charge");String pic = (String) sourceAsMap.get("pic");String description = (String) sourceAsMap.get("description");String teachplan = (String) sourceAsMap.get("teachplan");CoursePub coursePub = new CoursePub();coursePub.setId(courseId);coursePub.setName(name);coursePub.setPic(pic);coursePub.setGrade(grade);coursePub.setTeachplan(teachplan);coursePub.setDescription(description);//设置map对象map.put(courseId,coursePub);}return map;} 测试 使用 swagger-ui 或 postman 测试查询课程信息接口。 0x04 前端开发 配置NGINX虚拟主机 学习中心的二级域名为 ucenter.xuecheng.com ,我们在 nginx 中配置 ucenter 虚拟主机。 学成网用户中心server {listen 80;server_name ucenter.xuecheng.com;个人中心location / {proxy_pass http://ucenter_server_pool;} } 前端ucenterupstream ucenter_server_pool{server 127.0.0.1:7081 weight=10;server 127.0.0.1:13000 weight=10;} 在学习中心要调用搜索的 API,使用 Nginx 解决代理,如下图: 在 ucenter 虚拟主机下配置搜索 Api 代理路径 后台搜索(公开api)upstream search_server_pool{server 127.0.0.1:40100 weight=10;} 学成网用户中心server {listen 80;server_name ucenter.xuecheng.com;个人中心location / {proxy_pass http://ucenter_server_pool;}后端搜索服务location /openapi/search/ {proxy_pass http://search_server_pool/search/;} } 前端 API 方法 在学习中心 xc-ui-pc-leanring 对课程信息的查询属于基础常用功能,所以我们将课程查询的 api 方法定义在base 模块下,如下图: 在system.js 中定义课程查询方法: import http from './public'export const course_view = id => {return http.requestGet('/openapi/search/course/getdetail/'+id);} 前端 API 方法调用 在 learning_video.vue 页面中调用课程信息查询接口得到课程计划,将课程计划json 串转成对象。 xc-ui-pc-leanring/src/module/course/page/learning_video.vue 1、定义视图 课程计划 <!--课程计划部分代码--><div class="navCont"><div class="course-weeklist"><div class="nav nav-stacked" v-for="(teachplan_first, index) in teachplanList"><div class="tit nav-justified text-center"><i class="pull-left glyphicon glyphicon-th-list"></i>{ {teachplan_first.pname} }<i class="pull-right"></i></div><li v-if="teachplan_first.children!=null" v-for="(teachplan_second, index) in teachplan_first.children"><i class="glyphicon glyphicon-check"></i><a :href="url" @click="study(teachplan_second.id)">{ {teachplan_second.pname} }</a></li><!-- <div class="tit nav-justified text-center"><i class="pull-left glyphicon glyphicon-th-list"></i>第一章<i class="pull-right"></i></div><li ><i class="glyphicon glyphicon-check"></i><a :href="url" >第一节</a></li>--><!--<li><i class="glyphicon glyphicon-unchecked"></i>为什么分为A、B、C部分</li>--></div></div></div> 课程名称 <div class="top text-center">{ {coursename} }</div> 定义数据对象 data() {return {url:'',//当前urlcourseId:'',//课程idchapter:'',//章节Idcoursename:'',//课程名称coursepic:'',//课程图片teachplanList:[],//课程计划playerOptions: {//播放参数autoplay: false,controls: true,sources: [{type: "application/x-mpegURL",src: ''}]},} } 在 created 钩子方法中获取课程信息 created(){//当前请求的urlthis.url = window.location//课程idthis.courseId = this.$route.params.courseId//章节idthis.chapter = this.$route.params.chapter//查询课程信息systemApi.course_view(this.courseId).then((view_course)=>{if(!view_course || !view_course[this.courseId]){this.$message.error("获取课程信息失败,请重新进入此页面!")return ;} let courseInfo = view_course[this.courseId]console.log(courseInfo)this.coursename = courseInfo.nameif(courseInfo.teachplan){let teachplan = JSON.parse(courseInfo.teachplan);this.teachplanList = teachplan.children;} })}, 测试 在浏览器请求:http://ucenter.xuecheng.com//learning/4028e581617f945f01617f9dabc40000/0 4028e581617f945f01617f9dabc40000:第一个参数为课程 id,测试时从 ES索引库找一个课程 id 0:第二个参数为课程计划 id,此参数用于点击课程计划播放视频。 如果出现跨域问题,但是确定已经配置了跨域,请尝试结束所以 nginx.exe 的进程 和 清空浏览器缓存。 如果还没有解决?重启电脑试试。 二、学习页面:获取视频播放地址 0x01 需求分析 用户进入在线学习页面,点击课程计划将播放该课程计划对应的教学视频。 业务流程如下: 业务流程说明: 1、用户进入在线学习页面,页面请求搜索服务获取课程信息(包括课程计划信息)并且在页面展示。 2、在线学习请求学习服务获取视频播放地址。 3、学习服务校验当前用户是否有权限学习,如果没有权限学习则提示用户。 4、学习服务校验通过,请求搜索服务获取课程媒资信息。 5、搜索服务请求ElasticSearch获取课程媒资信息。 为什么要请求 ElasticSearch 查询课程媒资信息? 出于性能的考虑,公开查询课程信息从搜索服务查询,分摊 mysql 数据库的访问压力。 什么时候将课程媒资信息存储到 ElasticSearch 中? 课程媒资信息是在课程发布的时候存入 ElasticSearch,因为课程发布后课程信息将基本不再修改。 0x02 课程发布:储存媒资信息 需求分析 课程媒资信息是在课程发布的时候存入 ElasticSearch 索引库,因为课程发布后课程信息将基本不再修改,具体的业务流程如下。 1、课程发布,向课程媒资信息表写入数据。 1)根据课程 id 删除 teachplanMediaPub 中的数据 2)根据课程 id 查询 teachplanMedia 数据 3)将查询到的 teachplanMedia 数据插入到 teachplanMediaPub 中 2、Logstash 定时扫描课程媒资信息表,并将课程媒资信息写入索引库。 数据模型 在 xc_course 数据库创建课程计划媒资发布表: CREATE TABLE teachplan_media_pub (teachplan_id varchar(32) NOT NULL COMMENT '课程计划id',media_id varchar(32) NOT NULL COMMENT '媒资文件id',media_fileoriginalname varchar(128) NOT NULL COMMENT '媒资文件的原始名称',media_url varchar(256) NOT NULL COMMENT '媒资文件访问地址',courseid varchar(32) NOT NULL COMMENT '课程Id',timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT'logstash使用',PRIMARY KEY (teachplan_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 数据模型类如下: package com.xuecheng.framework.domain.course;import lombok.Data;import lombok.ToString;import org.hibernate.annotations.GenericGenerator;import javax.persistence.;import java.io.Serializable;import java.util.Date;@Data@ToString@Entity@Table(name="teachplan_media_pub")@GenericGenerator(name = "jpa-assigned", strategy = "assigned")public class TeachplanMediaPub implements Serializable {private static final long serialVersionUID = -916357110051689485L;@Id@GeneratedValue(generator = "jpa-assigned")@Column(name="teachplan_id")private String teachplanId;@Column(name="media_id")private String mediaId;@Column(name="media_fileoriginalname")private String mediaFileOriginalName;@Column(name="media_url")private String mediaUrl;@Column(name="courseid")private String courseId;@Column(name="timestamp")private Date timestamp;//时间戳} Dao 创建 TeachplanMediaPub 表的 Dao,向 TeachplanMediaPub 存储信息采用先删除该课程的媒资信息,再添加该课程的媒资信息,所以这里定义根据课程 id 删除课程计划媒资方法: public interface TeachplanMediaPubRepository extends JpaRepository<TeachplanMediaPub, String> {//根据课程id删除课程计划媒资信息long deleteByCourseId(String courseId);} 从TeachplanMedia查询课程计划媒资信息 //从TeachplanMedia查询课程计划媒资信息public interface TeachplanMediaRepository extends JpaRepository<TeachplanMedia, String> {List<TeachplanMedia> findByCourseId(String courseId);} Service 编写保存课程计划媒资信息方法,并在课程发布时调用此方法。 1、保存课程计划媒资信息方法 本方法采用先删除该课程的媒资信息,再添加该课程的媒资信息,在 CourseService 下定义该方法 //保存课程计划媒资信息private void saveTeachplanMediaPub(String courseId){//查询课程媒资信息List<TeachplanMedia> byCourseId = teachplanMediaRepository.findByCourseId(courseId);if(byCourseId == null) return; //没有查询到媒资数据则直接结束该方法//将课程计划媒资信息储存到待索引表//删除原有的索引信息teachplanMediaPubRepository.deleteByCourseId(courseId);//一个课程可能会有多个媒资信息,遍历并使用list进行储存List<TeachplanMediaPub> teachplanMediaPubList = new ArrayList<>();for (TeachplanMedia teachplanMedia: byCourseId) {TeachplanMediaPub teachplanMediaPub = new TeachplanMediaPub();BeanUtils.copyProperties(teachplanMedia, teachplanMediaPub);teachplanMediaPubList.add(teachplanMediaPub);}//保存所有信息teachplanMediaPubRepository.saveAll(teachplanMediaPubList);} 2、课程发布时调用此方法 修改课程发布的 coursePublish 方法: ....//保存课程计划媒资信息到待索引表saveTeachplanMediaPub(courseId);//页面urlString pageUrl = cmsPostPageResult.getPageUrl();return new CoursePublishResult(CommonCode.SUCCESS,pageUrl);..... 测试 测试课程发布后是否成功将课程媒资信息存储到 teachplan_media_pub 中,测试流程如下: 1、指定一个课程 2、为课程计划添加课程媒资 3、执行课程发布 4、观察课程计划媒资信息是否存储至 teachplan_media_pub 中 注意:由于此测试仅用于测试发布课程计划媒资信息的功能,可暂时将 cms页面发布的功能暂时屏蔽,提高测试效率。 测试结果如下 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vrzs5589-1595567273126)(https://qnoss.codeyee.com/20200704_15/image7)] 0x03 Logstash:扫描课程计划媒资 Logstash 定时扫描课程媒资信息表,并将课程媒资信息写入索引库。 创建索引 1、创建 xc_course_media 索引 2、并向此索引创建如下映射 POST: http://localhost:9200/xc_course_media/doc/_mapping {"properties" : {"courseid" : {"type" : "keyword"},"teachplan_id" : {"type" : "keyword"},"media_id" : {"type" : "keyword"},"media_url" : {"index" : false,"type" : "text"},"media_fileoriginalname" : {"index" : false,"type" : "text"} }} 索引创建成功 创建模板文件 在 logstach 的 config 目录文件 xc_course_media_template.json 文件路径为 %ES_ROOT_DIR%/logstash6.8.8/config/xc_course_media_template.json %ES_ROOT_DIR% 为 ElasticSearch 和 logstash 的安装目录 内容如下: {"mappings" : {"doc" : {"properties" : {"courseid" : {"type" : "keyword"},"teachplan_id" : {"type" : "keyword"},"media_id" : {"type" : "keyword"},"media_url" : {"index" : false,"type" : "text"},"media_fileoriginalname" : {"index" : false,"type" : "text"} }},"template" : "xc_course_media"} } 配置 mysql.conf 在logstash的 config 目录下配置 mysql_course_media.conf 文件供 logstash 使用,logstash 会根据 mysql_course_media.conf 文件的配置的地址从 MySQL 中读取数据向 ES 中写入索引。 参考https://www.elastic.co/guide/en/logstash/current/plugins-inputs-jdbc.html 配置输入数据源和输出数据源。 input {stdin {} jdbc {jdbc_connection_string => "jdbc:mysql://localhost:3306/xc_course?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC" 数据库信息jdbc_user => "root"jdbc_password => "123123" MYSQL 驱动地址,修改为maven仓库对应的位置jdbc_driver_library => "D:/soft/apache-maven-3.5.4/repository/mysql/mysql-connector-java/5.1.40/mysql-connector-java-5.1.40.jar" the name of the driver class for mysqljdbc_driver_class => "com.mysql.jdbc.Driver"jdbc_paging_enabled => "true"jdbc_page_size => "50000"要执行的sql文件statement_filepath => "/conf/course.sql"statement => "select from teachplan_media_pub where timestamp > date_add(:sql_last_value,INTERVAL 8 HOUR)"定时配置schedule => " "record_last_run => truelast_run_metadata_path => "D:/soft/elasticsearch/logstash-6.8.8/config/xc_course_media_metadata"} } output {elasticsearch {ES的ip地址和端口hosts => "localhost:9200"hosts => ["localhost:9200","localhost:9202","localhost:9203"]ES索引库名称index => "xc_course_media"document_id => "%{teachplan_id}"document_type => "doc"template => "D:/soft/elasticsearch/logstash-6.8.8/config/xc_course_media_template.json"template_name =>"xc_course_media"template_overwrite =>"true"} stdout {日志输出codec => json_lines} } 启动 logstash.bat 启动 logstash.bat 采集 teachplan_media_pub 中的数据,向 ES 写入索引。 logstash.bat -f ../config/mysql_course_media.conf 课程发布成功后,Logstash 会自动参加 teachplan_media_pub 表中新增的数据,效果如下 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ILPBxfXi-1595567273134)(https://qnoss.codeyee.com/20200704_15/image10)] Logstash多实例运行 由于之前我们还启动了一个 Logstash 对课程的发布信息进行采集,所以如果想两个 logstash 实例同时运行,因为每个实例都有一个.lock文件,所以不能使用同一个目录来存放数据,所以我们需要使用 --path.data= 为每个实例指定单独的数据目录,具体的代码如下: 该配置是在windows下进行的 课程发布实例 logstash_start_course_pub.bat @title logstash in course_publogstash.bat -f ..\config\mysql.conf --path.data=../data/course_pub 课程计划媒体发布实例 logstash_start_teachplan_media.bat @title logstash i n teachplan_media_publogstash.bat -f ../config/mysql_course_media.conf --path.data=../data/teachplan_media/ 同时运行效果如下 0x04 搜素服务:查询课程媒资接口 需求分析 搜索服务 提供查询课程媒资接口,此接口供学习服务调用。 Api接口定义 @ApiOperation("根据课程计划查询媒资信息")public TeachplanMediaPub getmedia(String teachplanId); Service 1、配置课程计划媒资索引库等信息 在 application.yml 中配置 xuecheng:elasticsearch:hostlist: ${eshostlist:127.0.0.1:9200} 多个结点中间用逗号分隔course:index: xc_coursetype: docsource_field: id,name,grade,mt,st,charge,valid,pic,qq,price,price_old,status,studymodel,teachmode,expires,pub_time,start_time,end_timemedia:index: xc_course_mediatype: docsource_field: courseid,media_id,media_url,teachplan_id,media_fileoriginalname 2、service 方法开发 在 课程搜索服务 中定义课程媒资查询接口,为了适应后续需求,service 参数定义为数组,可一次查询多个课程计划的媒资信息。 / 根据一个或者多个课程计划id查询媒资信息 @param teachplanIds 课程id @return QueryResponseResult/public QueryResponseResult<TeachplanMediaPub> getmedia(String [] teachplanIds){//设置索引SearchRequest searchRequest = new SearchRequest(media_index);//设置类型searchRequest.types(media_type);//创建搜索源对象SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//源字段过滤String[] media_index_arr = media_field.split(",");searchSourceBuilder.fetchSource(media_index_arr, new String[]{});//查询条件,根据课程计划id查询(可以传入多个课程计划id)searchSourceBuilder.query(QueryBuilders.termsQuery("teachplan_id", teachplanIds));searchRequest.source(searchSourceBuilder);SearchResponse searchResponse = null;try {searchResponse = restHighLevelClient.search(searchRequest);} catch (IOException e) {e.printStackTrace();}//获取结果SearchHits hits = searchResponse.getHits();long totalHits = hits.getTotalHits();SearchHit[] searchHits = hits.getHits();//数据列表List<TeachplanMediaPub> teachplanMediaPubList = new ArrayList<>();for(SearchHit hit:searchHits){TeachplanMediaPub teachplanMediaPub =new TeachplanMediaPub();Map<String, Object> sourceAsMap = hit.getSourceAsMap();//取出课程计划媒资信息String courseid = (String) sourceAsMap.get("courseid");String media_id = (String) sourceAsMap.get("media_id");String media_url = (String) sourceAsMap.get("media_url");String teachplan_id = (String) sourceAsMap.get("teachplan_id");String media_fileoriginalname = (String) sourceAsMap.get("media_fileoriginalname");teachplanMediaPub.setCourseId(courseid);teachplanMediaPub.setMediaUrl(media_url);teachplanMediaPub.setMediaFileOriginalName(media_fileoriginalname);teachplanMediaPub.setMediaId(media_id);teachplanMediaPub.setTeachplanId(teachplan_id);//将对象加入到列表中teachplanMediaPubList.add(teachplanMediaPub);}//构建返回课程媒资信息对象QueryResult<TeachplanMediaPub> queryResult = new QueryResult<>();queryResult.setList(teachplanMediaPubList);queryResult.setTotal(totalHits);return new QueryResponseResult<TeachplanMediaPub>(CommonCode.SUCCESS,queryResult);} Controller / 根据课程计划id搜索发布后的媒资信息 @param teachplanId @return/@GetMapping(value="/getmedia/{teachplanId}")@Overridepublic TeachplanMediaPub getmedia(@PathVariable("teachplanId") String teachplanId) {//为了service的拓展性,所以我们service接收的是数组作为参数,以便后续开发查询多个ID的接口String[] teachplanIds = new String[]{teachplanId};//通过service查询ES获取课程媒资信息QueryResponseResult<TeachplanMediaPub> mediaPubQueryResponseResult = esCourseService.getmedia(teachplanIds);QueryResult<TeachplanMediaPub> queryResult = mediaPubQueryResponseResult.getQueryResult();if(queryResult!=null&& queryResult.getList()!=null&& queryResult.getList().size()>0){//返回课程计划对应课程媒资return queryResult.getList().get(0);} return new TeachplanMediaPub();} 测试 使用 swagger-ui 和 postman 测试课程媒资查询接口。 三、在线学习:接口开发 0x01 需求分析 根据下边的业务流程,本章节完成前端学习页面请求学习服务获取课程视频地址,并自动播放视频。 0x02 搭建开发环境 1、创建数据库 创建 xc_learning 数据库,学习数据库将记录学生的选课信息、学习信息。 导入:资料/xc_learning.sql 2、创建学习服务工程 参考课程管理服务工程结构,创建学习服务工程: 导入:资料/xc-service-learning.zip 项目工程结构如下 0x03 Api接口 此 api 接口是课程学习页面请求学习服务获取课程学习地址。 定义返回值类型: package com.xuecheng.framework.domain.learning.response;import com.xuecheng.framework.model.response.ResponseResult;import com.xuecheng.framework.model.response.ResultCode;import lombok.Data;import lombok.NoArgsConstructor;import lombok.ToString;@Data@ToString@NoArgsConstructorpublic class GetMediaResult extends ResponseResult {public GetMediaResult(ResultCode resultCode, String fileUrl) {super(resultCode);this.fileUrl = fileUrl;}//媒资文件播放地址private String fileUrl;} 定义接口,学习服务根据传入课程 ID、章节 Id(课程计划 ID)来取学习地址。 @Api(value = "录播课程学习管理",description = "录播课程学习管理")public interface CourseLearningControllerApi {@ApiOperation("获取课程学习地址")public GetMediaResult getMediaPlayUrl(String courseId,String teachplanId);} 0x04 服务端开发 需求分析 学习服务根据传入课程ID、章节Id(课程计划ID)请求搜索服务获取学习地址。 搜索服务注册Eureka 学习服务要调用搜索服务查询课程媒资信息,所以需要将搜索服务注册到 eureka 中。 1、查看服务名称是否为 xc-service-search 注意修改application.xml中的服务名称:spring:application:name: xc‐service‐search 2、配置搜索服务的配置文件 application.yml,加入 Eureka 配置 如下: eureka:client:registerWithEureka: true 服务注册开关fetchRegistry: true 服务发现开关serviceUrl: Eureka客户端与Eureka服务端进行交互的地址,多个中间用逗号分隔defaultZone: ${EUREKA_SERVER:http://localhost:50101/eureka/,http://localhost:50102/eureka/}instance:prefer-ip-address: true 将自己的ip地址注册到Eureka服务中ip-address: ${IP_ADDRESS:127.0.0.1}instance-id: ${spring.application.name}:${server.port} 指定实例idribbon:MaxAutoRetries: 2 最大重试次数,当Eureka中可以找到服务,但是服务连不上时将会重试,如果eureka中找不到服务则直接走断路器MaxAutoRetriesNextServer: 3 切换实例的重试次数OkToRetryOnAllOperations: false 对所有操作请求都进行重试,如果是get则可以,如果是post,put等操作没有实现幂等的情况下是很危险的,所以设置为falseConnectTimeout: 5000 请求连接的超时时间ReadTimeout: 6000 请求处理的超时时间 3、添加 eureka 依赖 <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring‐cloud‐starter‐netflix‐eureka‐client</artifactId></dependency> 4、修改启动类,在class上添加如下注解: @EnableDiscoveryClient 搜索服务客户端 在 学习服务 创建搜索服务的客户端接口,此接口会生成代理对象,调用搜索服务: package com.xuecheng.learning.client;import com.xuecheng.framework.domain.course.TeachplanMediaPub;import org.springframework.cloud.openfeign.FeignClient;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;@FeignClient(value = "xc‐service‐search")public interface CourseSearchClient {@GetMapping(value="/getmedia/{teachplanId}")public TeachplanMediaPub getmedia(@PathVariable("teachplanId") String teachplanId);} 自定义错误代码 我们在 com.xuecheng.framework.domain.learning.response 包下自定义一个错误消息模型 package com.xuecheng.framework.domain.learning.response;import com.xuecheng.framework.model.response.ResultCode;import lombok.ToString;@ToStringpublic enum LearningCode implements ResultCode {LEARNING_GET_MEDIA_ERROR(false,23001,"学习中心获取媒资信息错误!");//操作代码boolean success;//操作代码int code;//提示信息String message;private LearningCode(boolean success, int code, String message){this.success = success;this.code = code;this.message = message;}@Overridepublic boolean success() {return success;}@Overridepublic int code() {return code;}@Overridepublic String message() {return message;} } 该消息模型基于 ResultCode 来实现,代码如下 package com.xuecheng.framework.model.response;/ Created by mrt on 2018/3/5. 10000-- 通用错误代码 22000-- 媒资错误代码 23000-- 用户中心错误代码 24000-- cms错误代码 25000-- 文件系统/public interface ResultCode {//操作是否成功,true为成功,false操作失败boolean success();//操作代码int code();//提示信息String message(); 从 ResultCode 中我们可以看出,我们约定了用户中心的错误代码使用 23000,所以我们定义的一些错误信息的代码就从 23000 开始计数。 Service 在学习服务中定义 service 方法,此方法远程请求课程管理服务、媒资管理服务获取课程学习地址。 package com.xuecheng.learning.service.impl;import com.netflix.discovery.converters.Auto;import com.xuecheng.framework.domain.course.TeachplanMediaPub;import com.xuecheng.framework.domain.learning.response.GetMediaResult;import com.xuecheng.framework.exception.ExceptionCast;import com.xuecheng.framework.model.response.CommonCode;import com.xuecheng.learning.client.CourseSearchClient;import com.xuecheng.learning.service.LearningService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class LearningServiceImpl implements LearningService {@AutowiredCourseSearchClient courseSearchClient;/ 远程调用搜索服务获取已发布媒体信息中的url @param courseId 课程id @param teachplanId 媒体信息id @return/@Overridepublic GetMediaResult getMediaPlayUrl(String courseId, String teachplanId) {//校验学生权限,是否已付费等//远程调用搜索服务进行查询媒体信息TeachplanMediaPub mediaPub = courseSearchClient.getmedia(teachplanId);if(mediaPub == null) ExceptionCast.cast(CommonCode.FAIL);return new GetMediaResult(CommonCode.SUCCESS, mediaPub.getMediaUrl());} } Controller 调用 service 根据课程计划 id 查询视频播放地址: @RestController@RequestMapping("/learning/course")public class CourseLearningController implements CourseLearningControllerApi {@AutowiredLearningService learningService;@Override@GetMapping("/getmedia/{courseId}/{teachplanId}")public GetMediaResult getMediaPlayUrl(@PathVariable String courseId, @PathVariable String teachplanId) {//获取课程学习地址return learningService.getMedia(courseId, teachplanId);} } 测试 使用 swagger-ui 或postman 测试学习服务查询课程视频地址接口。 0x05 前端开发 需求分析 需要在学习中心前端页面需要完成如下功能: 1、进入课程学习页面需要带上 课程 Id参数及课程计划Id的参数,其中 课程 Id 参数必带,课程计划 Id 可以为空。 2、进入页面根据 课程 Id 取出该课程的课程计划显示在右侧。 3、进入页面后判断如果请求参数中有课程计划 Id 则播放该章节的视频。 4、进入页面后判断如果 课程计划id 为0则需要取出本课程第一个 课程计划的Id,并播放第一个课程计划的视频。 进入到模块 xc-ui-pc-leanring/src/module/course api方法 let sysConfig = require('@/../config/sysConfig')let apiUrl = sysConfig.xcApiUrlPre;/获取播放地址/export const get_media = (courseId,chapter) => {return http.requestGet(apiUrl+'/api/learning/course/getmedia/'+courseId+'/'+chapter);} 配置代理 在 Nginx 中的 ucenter.xuecheng.com 虚拟主机中配置 /api/learning/ 的路径转发,此url 请转发到学习服务。 学习服务upstream learning_server_pool{server 127.0.0.1:40600 weight=10;}学成网用户中心server {listen 80;server_name ucenter.xuecheng.com;个人中心location / {proxy_pass http://ucenter_server_pool;}后端搜索服务location /openapi/search/ {proxy_pass http://search_server_pool/search/; }学习服务location ^~ /api/learning/ {proxy_pass http://learning_server_pool/learning/;} } 视频播放页面 1、如果传入的课程计划id为0则取出第一个课程计划id 在 created 钩子方法中完成 created(){//当前请求的urlthis.url = window.location//课程idthis.courseId = this.$route.params.courseId//章节idthis.chapter = this.$route.params.chapter//查询课程信息systemApi.course_view(this.courseId).then((view_course)=>{if(!view_course || !view_course[this.courseId]){this.$message.error("获取课程信息失败,请重新进入此页面!")return ;}let courseInfo = view_course[this.courseId]console.log(courseInfo)this.coursename = courseInfo.nameif(courseInfo.teachplan){console.log("准备开始播放视频")let teachplan = JSON.parse(courseInfo.teachplan);this.teachplanList = teachplan.children;//开始学习if(this.chapter == "0" || !this.chapter){//取出第一个教学计划this.chapter = this.getFirstTeachplan();console.log("第一个教学计划id为 ",this.chapter);this.study(this.chapter);}else{this.study(this.chapter);} }})}, 取出第一个章节 id,用户未输入课程计划 id 或者输入为 0 时,播放第一个。 //取出第一个章节getFirstTeachplan(){for(var i=0;i<this.teachplanList.length;i++){let firstTeachplan = this.teachplanList[i];//如果当前children存在,则取出第一个返回if(firstTeachplan.children && firstTeachplan.children.length>0){let secondTeachplan = firstTeachplan.children[0];return secondTeachplan.id;} }return ;}, 开始学习: //开始学习study(chapter){// 获取播放地址courseApi.get_media(this.courseId,chapter).then((res)=>{if(res.success){let fileUrl = sysConfig.videoUrl + res.fileUrl//播放视频this.playvideo(fileUrl)}else if(res.message){this.$message.error(res.message)}else{this.$message.error("播放视频失败,请刷新页面重试")} }).catch(res=>{this.$message.error("播放视频失败,请刷新页面重试")});}, 2、点击右侧课程章节切换播放 在原有代码基础上添加 click 事件,点击调用开始学习方法(study)。 <li v‐if="teachplan_first.children!=null" v‐for="(teachplan_second, index) inteachplan_first.children"><i class="glyphicon glyphicon‐check"></i><a :href="url" @click="study(teachplan_second.id)">{ {teachplan_second.pname} }</a></li> 3、地址栏路由url变更 这里需要注意一个问题,在用户点击课程章节切换播放时,地址栏的 url 也应该同步改变为当前所选择的课程计划 id 4、在线学习按钮 将 learnstatus 默认更改为 1,这样就能显示出马上学习的按钮,方便我们后续的集成测试。 文件路径为 xc-ui-pc-static-portal/include/course_detail_dynamic.html 部分代码块如下 <script>var body= new Vue({ //创建一个Vue的实例el: "body", //挂载点是id="app"的地方data: {editLoading: false,title:'测试',courseId:'',charge:'',//203001免费,203002收费learnstatus: 1 ,//课程状态,1:马上学习,2:立即报名、3:立即购买course:{},companyId:'template',company_stat:[],course_stat:{"s601001":"","s601002":"","s601003":""} }, 简单的测试 访问在线学习页面:http://ucenter.xuecheng.com//learning/课程id/课程计划id 通过 url 传入两个参数:课程id 和 课程计划id 如果没有课程计划则传入0 测试项目如下: 1、传入正确的课程id、课程计划id,自动播放本章节的视频 2、传入正确的课程id、课程计划id传入0,自动播放第一个视频 3、传入错误的课程id 或 课程计划id,提示错误信息。 4、通过右侧章节目录切换章节及播放视频。 访问: http://ucenter.xuecheng.com//learning/4028e58161bcf7f40161bcf8b77c0000/4028e58161bd18ea0161bd1f73190008 传入正确的课程id、课程计划id,自动播放本章节的视频 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ef0xxym7-1595567273153)(https://qnoss.codeyee.com/20200704_15/image17)] 传入正确的课程id、课程计划id传入0,自动播放第一个视频 访问 http://ucenter.xuecheng.com//learning/4028e58161bcf7f40161bcf8b77c0000/0 识别出第一个课程计划的 id 需要注意的是这里的 chapter 参数是我自己在 study 函数里加上去的,可以忽略。 传入错误的课程id或课程计划id,提示错误信息。 通过右侧章节目录切换章节及播放视频。 点击章节即可播放,但是点击制定章节后 url 没有发生改变,这个问题暂时还没有解决,关注笔记后面的内容。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TOGdxwb4-1595567273158)(https://qnoss.codeyee.com/20200704_15/image20)] 完整的测试 准备工作 启动 RabbitMQ,启动 Logstash、ElasticSearch 建议把所有后端服务都开起来 启动 前端静态门户、启动 nginx 、启动课程管理前端 我们整理一下测试的流程 上传两个媒资视频文件,用于测试 进入到课程管理,为课程计划选择媒资信息 发布课程,等待 logstash 将数据采集到 ElasticSearch 的索引库中 进入学成网主页,点击课程,进入到搜索门户页面 搜索课程,进入到课程详情页面 点击开始学习,进入到课程学习页面,选择课程计划中的一个章节进行学习。 1、上传文件 首先我们使用之前开发的媒资管理模块,上传两个视频文件用于测试。 第一个文件上传成功 一些问题 在上传第二个文件时,发生了错误,我们来检查一下问题出在了哪里 在媒体服务的控制台中可以看到,在 mergeChunks 方法在校验文件 md5 时候抛出了异常 我们在 MD5 校验这里打个断点,重新上传文件,分析一下问题所在。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OpEMZGI8-1595567273166)(https://qnoss.codeyee.com/20200704_15/image23)] 单步调试后发现,合并文件后的MD5值与用户上传的源文件值不相等 方案1:删除本地分块文件重新尝试上传 考虑到可能是在用户上传完 视频的分块文件时发生了一些问题,导致合并文件后与源文件的大小不等,导致MD5也不相同,这里我们把这个视频上传到本地的文件全部删除,在媒资上传页面重新上传文件。 对比所有分块文件的字节大小和本地源文件的大小,完全是相等的 删除所有文件后重新上传,md5值还是不等,考虑从调试一下文件合并的代码。 方案2:检查前端提交的MD5值是否正确 在查阅是否有其他的MD5值获取方案时,发现了一个使用 windows 本地命令获取文件MD5值的方法 certutil -hashfile .\19-在线学习接口-集成测试.avi md5 惊奇的发现,TM的原来是前端那边转换的MD5值不正确,后端这边是没有问题的。 从前面的图可以看出,本地和后端转换的都是以一个 f6f0 开头的MD5值 那么问题就出现在前端了,还需要花一些时间去分析一下,这里暂时就先告一段落,因为上传了几个文件测试中只有这一个文件出现了问题。 2、为课程计划选择媒资信息 进入到一个课程的管理页面 http://localhost:12000//course/manage/baseinfo/4028e58161bcf7f40161bcf8b77c0000 将刚才我们上传的媒资文件的信息和课程计划绑定 选择效果如下 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-epKaqzCD-1595567273178)(https://qnoss.codeyee.com/20200704_15/image29)] 2、发布课程,等待 logstash 从 course_pub 以及 teachplan_media_pub 表中采集数据到 ElasticSearch 当中 发布成功后,我们可以从 teachplan_media_pub 表中看到刚才我们发布的媒资信息 再观察 Logstash 的控制台,发现两个 Logstash 的实例都对更新的课程发布信息进行了采集 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hTUve2ik-1595567273183)(https://qnoss.codeyee.com/20200704_15/image32)] 3、前端门户测试 打开我们的门户主站 http://www.xuecheng.com/ [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4wZe9R84-1595567273185)(https://qnoss.codeyee.com/20200704_15/image33)] 点击导航栏的课程,进入到我们的搜索门户页面 如果无法进入到搜索门户,请检查你的 xc-ui-pc-portal 前端工程是否已经启动 进入到搜索门户后,可以看到一些初始化时搜索的课程数据,默认是搜索第一页的数据,每页2个课程。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BJ1AKoJb-1595567273187)(https://qnoss.codeyee.com/20200704_15/image34)] 我们可以测试搜索一下前面我们选择媒资信息时所用的课程 点击课程,进入到课程详情页面,然后再点击开始学习。 点击马上学习后,会进入到该课程的在线学习页面,默认自动播放我们第一个课程计划中的视频。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tcuLWnf2-1595567273193)(https://qnoss.codeyee.com/20200704_15/image37)] 我们可以在右侧的目录中选择第二个课程计划,会自动播放所选的课程计划所对应的媒资视频播放地址,该 播放地址正是我们刚才通过 Logstash 自动采集到 ElasticSearch 的索引信息,效果图如下 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Cvi9Dr0Y-1595567273195)(https://qnoss.codeyee.com/20200704_15/image38)] 四、待完善的一些功能 课程发布前,校验课程计划里面是否包含二级课程计划 课程发布前,校验课程计划信息里面是否全部包含媒资信息 删除媒资信息,并且同步删除ES中的索引 在获取该课程的播放地址时校验用户的合法、 在线学习页面,点击右侧目录中的课程计划同时改变url中的课程计划地址 视频文件 19-在线学习接口-集成测试.avi 前端上传时提交的MD5值不正确 😁 认识作者 作者:👦 LCyee ,全干型代码🐕 自建博客:https://www.codeyee.com 记录学习以及项目开发过程中的笔记与心得,记录认知迭代的过程,分享想法与观点。 CSDN 博客:https://blog.csdn.net/codeyee 记录和分享一些开发过程中遇到的问题以及解决的思路。 欢迎加入微服务练习生的队伍,一起交流项目学习过程中的一些问题、分享学习心得等,不定期组织一起刷题、刷项目,共同见证成长。 本篇文章为转载内容。原文链接:https://blog.csdn.net/codeyee/article/details/107558901。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-16 12:41:01
73
转载
Mahout
一、引言 在大数据时代,文本分类是一个重要的任务。Mahout,这可是个不得了的开源神器,专门用来处理大规模机器学习问题。甭管你的数据有多大、多复杂,它都能轻松应对。就拿文本分类来说吧,有了Mahout这个好帮手,你就能轻轻松松地对海量文本进行高效分类,简直就像给每篇文章都贴上合适的标签一样简单便捷!本文将介绍如何使用Mahout进行大规模文本分类。 二、安装Mahout 首先,我们需要下载并安装Mahout。你可以在Mahout的官方网站上找到最新的版本。 三、数据预处理 对于任何机器学习任务,数据预处理都是非常重要的一步。在Mahout中,我们可以使用JDOM工具对原始数据进行处理。以下是一个简单的例子: java import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; // 创建一个SAX解析器 SAXBuilder saxBuilder = new SAXBuilder(); // 解析XML文件 Document doc = saxBuilder.build("data.xml"); // 获取根元素 Element root = doc.getRootElement(); // 遍历所有子元素 for (Element element : root.getChildren()) { // 对每个子元素进行处理 } 四、特征提取 在Mahout中,我们可以使用TF-IDF算法来提取文本的特征。以下是一个简单的例子: java import org.apache.mahout.math.Vector; import org.apache.mahout.text.TfidfVectorizer; // 创建一个TF-IDF向量化器 TfidfVectorizer vectorizer = new TfidfVectorizer(); // 将文本转换为向量 Vector vector = vectorizer.transform(text); 五、模型训练 在Mahout中,我们可以使用Naive Bayes、Logistic Regression等算法来进行模型训练。以下是一个简单的例子: java import org.apache.mahout.classifier.NaiveBayes; // 创建一个朴素贝叶斯分类器 NaiveBayes classifier = new NaiveBayes(); // 使用训练集进行训练 classifier.train(trainingData); 六、模型测试 在模型训练完成后,我们可以使用测试集对其进行测试。以下是一个简单的例子: java import org.apache.mahout.classifier.NaiveBayes; // 使用测试集进行测试 double accuracy = classifier.evaluate(testData); System.out.println("Accuracy: " + accuracy); 七、总结 通过上述步骤,我们就可以使用Mahout进行大规模文本分类了。其实呢,这只是个入门级别的例子,实际上咱们可能要面对更复杂的操作,像是给数据“洗洗澡”(预处理)、抽取出关键信息(特征提取),还有对模型进行深度调教(训练)这些步骤。希望这个教程能帮助你在实际工作中更好地使用Mahout。
2023-03-23 19:56:32
108
青春印记-t
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
unalias alias_name
- 删除已定义的别名。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"