前端技术
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
[使用GROUP BY处理重复数据]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Oracle
Oracle数据库中处理数据表重复记录的问题 在我们日常的Oracle数据库管理与开发过程中,数据完整性是一项至关重要的任务。有时候啊,因为各种乱七八糟的原因,我们的数据表可能会冒出一些重复的记录来,这就像是给咱们的数据一致性捣乱,还可能把业务逻辑也带偏了,带来不少麻烦呢。本文将深入探讨如何在Oracle数据库中检测并处理数据表中的重复记录问题,通过实例代码及探讨性话术,力求以生动、直观的方式展示解决之道。 1. 发现数据表中的重复记录 首先,我们需要确定哪些记录是重复的。这里,假设我们有一个名为Employees的数据表,其中可能存在ID和Email字段重复的情况: sql CREATE TABLE Employees ( ID INT PRIMARY KEY, Name VARCHAR2(50), Email VARCHAR2(50), JobTitle VARCHAR2(50) ); 为了找出所有Email字段重复的记录,我们可以使用GROUP BY和HAVING子句: sql SELECT Email, COUNT() FROM Employees GROUP BY Email HAVING COUNT() > 1; 这段SQL会返回所有出现次数大于1的邮箱地址,这就意味着这些邮箱存在重复记录。 2. 删除重复记录 识别出重复记录后,我们需要谨慎地删除它们,确保不破坏数据完整性。一种策略是保留每个重复组的第一条记录,并删除其他重复项。为此,我们可以创建临时表,并用ROW_NUMBER()窗口函数来标识每组重复记录的顺序: sql -- 创建临时表并标记重复记录的顺序 CREATE TABLE Temp_Employees AS SELECT ID, Name, Email, JobTitle, ROW_NUMBER() OVER(PARTITION BY Email ORDER BY ID) as RowNum FROM Employees; -- 删除临时表中RowNum大于1的重复记录 DELETE FROM Temp_Employees WHERE RowNum > 1; -- 将无重复记录的临时表数据回迁到原表 INSERT INTO Employees (ID, Name, Email, JobTitle) SELECT ID, Name, Email, JobTitle FROM Temp_Employees; -- 清理临时表 DROP TABLE Temp_Employees; 上述代码流程中,我们首先创建了一个临时表Temp_Employees,为每个Email字段相同的组分配行号(根据ID排序)。然后删除行号大于1的记录,即除每组第一条记录以外的所有重复记录。最后,我们将去重后的数据重新插入原始表并清理临时表。 3. 防止未来新增重复记录 为了避免将来再次出现此类问题,我们可以为容易重复的字段添加唯一约束。例如,对于上面例子中的Email字段: sql ALTER TABLE Employees ADD CONSTRAINT Unique_Email UNIQUE (Email); 这样,在尝试插入新的具有已存在Email值的记录时,Oracle将自动阻止该操作。 总结 处理Oracle数据库中的重复记录问题是一个需要细心和策略的过程。在这个过程中,咱们得把数据结构摸得门儿清,像老朋友一样灵活运用SQL查询和DML语句。同时呢,咱们也得提前打个“预防针”,确保以后不再犯同样的错误。在这一整个寻觅答案和解决问题的旅程中,我们不停地琢磨、动手实践、灵活变通,这恰恰就是人与科技亲密接触所带来的那种无法抗拒的魅力。希望本文中给出的实例和小窍门,能真正帮到您,让管理维护您的Oracle数据库变得轻轻松松,确保数据稳稳妥妥、整整齐齐的。
2023-02-04 13:46:08
48
百转千回
.net
...开发中,我们经常会与数据库打交道,特别是在.NET平台下,C作为主要的编程语言,其强大的功能使我们能够轻松地操作数据库。嘿,有时候生活就像个谜,对吧?比如,你费劲巴拉地在数据海洋里捞啊捞,想把好东西都装进集合里,结果却发现有几样宝贝竟然重复了!想知道这是咋回事吗?今天,咱们就一起解开这个小谜团,学学怎么聪明地避开重复,还能把重复的小伙伴处理得既简单又体面。走起! 二、C遍历数据库的基本原理 1.1 数据访问层概述 首先,让我们回顾一下在.NET中是如何通过ADO.NET或Entity Framework等ORM(对象关系映射)框架来连接和查询数据库的。例如,使用Entity Framework,我们可以这样获取数据: csharp using (var context = new MyDbContext()) { var query = context.MyTable.OrderBy("MyField"); var result = query.ToList(); } 这段代码创建了一个上下文对象,执行SQL查询(按"myField"排序),并将结果转换为List集合。 1.2 遍历与重复问题 当我们直接将查询结果存储到集合中时,如果数据库中有重复的记录,那么集合自然也会包含这些重复项。这是因为集合的默认行为是不进行去重的。 三、去重机制与解决方案 2.1 去重的基本概念 在.NET中,我们需要明确区分两种不同的去重方式:在内存中的去重和在数据库层面的去重。你知道吗,通常在我们拿到数据后,第一件事儿就是清理内存里的重复项,就像整理房间一样,要把那些重复的玩意儿挑出去。而在数据库那头,去重可就有点技术含量了,得靠咱们精心编写的SQL语句,就像侦探破案一样,一点一点找出那些隐藏的“双胞胎”记录。 2.2 内存层面的去重 如果我们希望在遍历后立即去除重复项,可以使用LINQ的Distinct()方法: csharp var uniqueResult = result.Distinct().ToList(); 这将创建一个新的集合,其中只包含唯一的元素。 2.3 SQL层面的去重 如果去重应在数据库层面完成,我们需要在查询语句中加入GROUP BY或DISTINCT关键字。例如: csharp var query = context.MyTable.OrderBy("MyField").GroupBy(x => x.MyField).Select(x => x.First()); 这将确保每组相同的"MyField"值仅返回一个结果。 四、优化与最佳实践 3.1 性能考虑 在处理大量数据时,直接在内存中去重可能会消耗大量资源。在这种情况下,我们可以选择分批处理或者使用数据库的分组功能。 3.2 数据一致性 在设计数据库表结构时,考虑使用唯一索引或主键来保证数据的唯一性,这将减少在应用程序中手动去重的需求。 五、结论 虽然.NET的C为我们提供了强大的数据库操作能力,但处理重复数据时需要我们细心考虑。要想在翻遍数据库的时候不被重复数据烦扰,关键在于透彻明白查询的门道,熟练掌握去重技巧,还得根据实际情况灵活运用策略,就像找宝藏一样,每次都能避开那些已经踩过的雷区。记住,编程不仅仅是语法,更是逻辑和思维的艺术。祝你在.NET的世界里游刃有余!
2024-04-07 11:24:46
434
星河万里_
转载文章
... 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
转载
Apache Pig
如何使用 UNION ALL 和 UNION 对多个表进行合并? 1. 引言 嘿,大家好!今天我要聊聊在大数据分析中一个非常实用的技术——Apache Pig中的UNION ALL和UNION操作。这两个招数在对付多个数据表时特别给力,能让我们轻松把一堆数据集整成一个,这样后面处理和分析起来就方便多了。接下来我打算好好聊聊这两个操作,还会举些实际例子,让你更容易上手,用起来也更溜! 2. UNION ALL vs UNION 选择合适的工具 首先,我们需要搞清楚UNION ALL和UNION的区别,因为它们虽然都能用来合并数据表,但在具体的应用场景中还是有一些细微差别的。 2.1 UNION ALL UNION ALL是直接将两个或多个数据表合并在一起,不管它们是否有重复的数据。这意味着如果两个表中有相同的数据行,这些行都会被保留下来。这就挺实用的,比如有时候你得把所有数据都拢在一起,一个都不能少,这时候就派上用场了。 2.2 UNION 相比之下,UNION会自动去除重复的数据行。也就是说,即使两个表中有完全相同的数据行,UNION也会只保留一份。这在你需要确保最终结果中没有重复项时特别有用。 3. 实战演练 动手合并数据 接下来,我们来看几个具体的例子,这样更容易理解这两个操作的实际应用。 3.1 示例一:简单的UNION ALL 假设我们有两个用户数据表users_1和users_2,每个表都包含了用户的ID和姓名: pig -- 定义第一个表 users_1 = LOAD 'data/users_1.txt' USING PigStorage(',') AS (id:int, name:chararray); -- 定义第二个表 users_2 = LOAD 'data/users_2.txt' USING PigStorage(',') AS (id:int, name:chararray); -- 使用UNION ALL合并两个表 merged_users_all = UNION ALL users_1, users_2; DUMP merged_users_all; 运行这段代码后,你会看到所有用户的信息都被合并到了一起,即使有重复的名字也不会被去掉。 3.2 示例二:利用UNION去除重复数据 现在,我们再来看一个稍微复杂一点的例子,假设我们有一个用户数据表users,其中包含了一些重复的用户记录: pig -- 加载数据 users = LOAD 'data/users.txt' USING PigStorage(',') AS (id:int, name:chararray); -- 去除重复数据 unique_users = UNION users; DUMP unique_users; 在这个例子中,UNION操作会自动帮你去除掉所有的重复行,这样你就得到了一个不包含任何重复项的用户列表。 4. 思考与讨论 在实际工作中,选择使用UNION ALL还是UNION取决于你的具体需求。如果你确实需要保留所有数据,包括重复项,那么UNION ALL是更好的选择。要是你特别在意最后的结果里头不要有重复的东西,那用UNION就对了。 另外,值得注意的是,UNION操作可能会比UNION ALL慢一些,因为它需要额外的时间来进行去重处理。所以,在处理大量数据时,需要权衡一下性能和数据的完整性。 5. 结语 好了,今天的分享就到这里了。希望能帮到你,在实际项目里更好地上手UNION ALL和UNION这两个操作。如果你有任何问题或者想要了解更多内容,欢迎随时联系我!
2025-01-12 16:03:41
81
昨夜星辰昨夜风
Datax
...被广泛应用于企业级大数据处理中。不过话说回来,现如今数据量蹭蹭地涨,大家伙儿对数据准不准、靠不靠谱这个问题可是越来越上心了。嘿,大家伙儿!接下来我要跟你们分享一下,在使用Datax这款工具时,如何从几个关键点出发,确保咱们处理的数据既准确又可靠,一步到位,稳稳当当的。 二、Datax的数据质量检查 在Datax的流程设置中,我们可以加入数据质量检查环节。比如,我们可以动手给数据安个过滤器,把那些重复的数据小弟踢出去,或者来个华丽变身,把不同类型的数据转换成我们需要的样子,这样一来,咱们手头的数据质量就能蹭蹭往上涨啦! 以下是一个简单的数据去重的例子: java public void execute(EnvContext envContext) { String sql = "SELECT FROM table WHERE id > 0"; TableInserter inserter = getTableInserter(envContext); try { inserter.init(); QueryResult queryResult = SqlRunner.run(sql, DatabaseType.H2); for (Row row : queryResult.getRows()) { inserter.insert(row); } } catch (Exception e) { throw new RuntimeException(e); } finally { inserter.close(); } } 在这个例子中,我们首先通过SQL查询获取到表中的所有非空行,然后将这些行插入到目标表中。这样,我们就避免了数据的重复插入。 三、Datax的数据验证 在数据传输过程中,我们还需要进行数据验证,以确保数据的正确性。例如,我们可以通过校验数据是否满足某种规则,来判断数据的有效性。 以下是一个简单的数据校验的例子: java public boolean isValid(String data) { return Pattern.matches("\\d{3}-\\d{8}", data); } 在这个例子中,我们定义了一个正则表达式,用于匹配手机号码。如果输入的数据恰好符合我们设定的这个正则表达式的规矩,那咱就可以拍着胸脯说,这个数据是完全OK的,是有效的。 四、Datax的数据清洗 在数据传输的过程中,我们还可能会遇到一些异常情况,如数据丢失、数据损坏等。在这种情况下,我们需要对数据进行清洗,以恢复数据的完整性和一致性。 以下是一个简单的数据清洗的例子: java public void cleanUp(EnvContext envContext) { String sql = "UPDATE table SET column1 = NULL WHERE column2 = 'error'"; SqlRunner.run(sql, DatabaseType.H2); } 在这个例子中,我们通过SQL语句,将表中column2为'error'的所有记录的column1字段设为NULL。这样,我们就清除了这些异常数据的影响。 五、结论 在使用Datax进行数据处理时,我们需要关注数据的质量、正确性和完整性等问题。通过严谨地给数据“体检”、反复验证其真实性,再仔仔细细地给它“洗个澡”,我们就能确保数据的准确度和可靠性蹭蹭上涨,真正做到让数据靠谱起来。同时呢,我们也要持续地改进咱们的数据处理方法,好让它们能灵活适应各种不断变化的数据环境,跟上时代步伐。
2023-05-23 08:20:57
281
柳暗花明又一村-t
Apache Solr
索引数据在特定时间点出现异常增长,导致存储空间不足 1. 引言 嗨,朋友们!今天我们要聊一个让很多Solr管理员头疼的问题——数据在某个时间点突然暴增,导致存储空间不足。这问题就像夏天突然来了一场暴雨,让我们措手不及。别慌啊,今天我们来聊聊怎么应对这个问题,让你的Solr系统变得更强大。 2. 数据异常增长的原因分析 首先,我们需要了解数据异常增长的原因。可能是因为: - 业务活动高峰:比如双十一这种大促销活动,可能会导致大量数据涌入。 - 数据清洗错误:如果数据清洗逻辑有误,可能会导致重复数据的产生。 - 系统配置问题:比如内存或磁盘空间不足,导致数据无法正常处理。 为了更好地理解问题,我们可以从日志入手。Solr的日志文件里通常会记下一些重要的东西,比如说数据入库的时间和频率之类的信息。通过查看这些日志,我们能更准确地定位问题所在。 3. 检查和优化存储空间 接下来,我们来看看具体的操作步骤。 3.1 检查当前存储空间 首先,我们需要检查当前的存储空间情况。可以使用以下命令来查看: bash df -h 这个命令会显示所有分区的使用情况。要是哪个分区眼看就要爆满,那咱们就得琢磨着怎么给它减减压了。 3.2 优化索引配置 如果存储空间不足,我们可以考虑调整索引的配置。比如,减少每个文档的大小,或者增加分片的数量。下面是一个简单的配置示例: xml TieredMergePolicy 10 5 在这个配置中,mergeFactor 控制了合并操作的频率,而 maxMergedSegmentMB 则控制了最大合并段的大小。你可以根据实际情况调整这些参数。 3.3 压缩和删除旧数据 另外一种方法是定期压缩和删除旧的数据。Solr提供了多种压缩策略,比如 forceMergeDeletesPct 和 expungeDeletes。下面是一个示例代码: java // Java 示例代码 SolrClient solr = new HttpSolrClient.Builder("http://localhost:8983/solr/mycollection").build(); solr.commit(new CommitCmd(true, true)); solr.close(); 这段代码会强制合并并删除标记为删除的文档。当然,你也可以设置定时任务来自动执行这些操作。 4. 监控和预警机制 最后,建立一套完善的监控和预警机制也是非常重要的。我们可以使用Prometheus、Grafana等工具来实时监控Solr的状态,并设置报警规则。这样一来,如果存储空间快不够了,系统就会自动发个警报,提醒管理员赶紧采取行动。 5. 总结 好了,今天的分享就到这里。希望这些方法能够帮助大家解决Solr存储空间不足的问题。记住,及时监控和优化是非常重要的。如果你还有其他问题,欢迎随时留言讨论! 总之,面对数据暴增的问题,我们需要冷静分析,合理规划,才能确保系统的稳定运行。希望这篇分享对你有所帮助,让我们一起努力,让Solr成为更强大的搜索工具吧!
2025-01-31 16:22:58
79
红尘漫步
Datax
一、引言 在大数据处理的过程中,Datax是一个不可或缺的工具。然而,在实际动手操作的过程中,我们可能会时不时碰到一些小插曲。比如在用Datax Writer这个插件往数据库里写入数据的时候,就可能会遇到一个头疼的问题——唯一键约束冲突。这就像是你拿着一堆数据卡片想放进一个已经塞得满满当当、每个格子都有编号的柜子里,结果发现有几张卡片上的编号跟柜子里已有卡片重复了,放不进去,这时候就尴尬啦!这个问题可能看似简单,但实则涉及到多个方面,包括数据预处理、数据库设计等。本文将针对这个问题进行详细的分析和解答。 二、问题描述 当我们使用Datax Writer插件向数据库中插入数据时,如果某个字段设置了唯一键约束,那么在插入重复数据时就会触发唯一键约束冲突。比如,我们弄了一个用户表,其中特意设了个独一无二的邮箱字段。不过,假如我们心血来潮,试图往这个表格里插两条一模一样的邮箱记录,那么系统就会毫不客气地告诉我们:哎呀,违反了唯一键约束,有冲突啦! 三、问题原因分析 首先,我们需要明白为什么会出现唯一键约束冲突。这是因为我们在插数据的时候,没对它们进行严格的“查重”工序,就直接一股脑儿地全塞进去了,结果就有了重复的数据跑进去啦。 其次,我们需要从数据库设计的角度来考虑这个问题。如果我们在设置数据库的时候,没把唯一键约束整对了,那么很可能就会出现唯一键冲突的情况。比如说,我们在用户表里给每位用户设了个独一无二的邮箱地址栏,然后在用户信息表里也整了个同样的邮箱地址栏,还把它设成了关键的主键。这样一来,当我们往里边输入数据的时候,就特别容易踩到“唯一键约束冲突”这个坑。 四、解决方案 对于上述问题,我们可以采取以下几种解决方案: 1. 数据预处理 在插入数据之前,我们需要对数据进行有效的去重处理。例如,我们可以使用Python的pandas库来进行数据去重。具体的代码如下: python import pandas as pd 读取数据 df = pd.read_csv('data.csv') 去重 df.drop_duplicates(inplace=True) 写入数据 df.to_sql('users', engine, if_exists='append', index=False) 这段代码会先读取数据,然后对数据进行去重处理,最后再将处理后的数据写入到数据库中。 2. 调整数据库设计 如果我们发现是由于数据库设计不当导致的唯一键约束冲突,那么我们就需要调整数据库的设计。比如说,我们能够把那些重复的字段挪到另一个表格里头,然后在往里填充数据的时候,就像牵线搭桥一样,通过外键让这两个表格建立起亲密的关系。 sql CREATE TABLE users ( id INT PRIMARY KEY, email VARCHAR(50) UNIQUE ); CREATE TABLE user_info ( id INT PRIMARY KEY, user_id INT, info VARCHAR(50), FOREIGN KEY (user_id) REFERENCES users(id) ); 在这段SQL语句中,我们将用户表中的email字段设置为唯一键,并将其移到了user_info表中,然后通过user_id字段将两个表关联起来。 五、总结 以上就是解决Datax Writer插件写入数据时触发唯一键约束冲突的方法。需要注意的是,这只是其中的一种方法,具体的操作方式还需要根据实际情况来确定。另外,为了让这种问题离我们远远的,咱们最好养成棒棒的数据处理习惯,别让数据重复“撞车”。
2023-10-27 08:40:37
721
初心未变-t
转载文章
...内容。 Python数据预处理的方法 数据预处理是数据分析、挖掘及机器学习应用中非常重要的一环。在数据预处理过程中,数据清洗和数据转换是必要的步骤。本文将介绍如何使用Python进行数据预处理工作,让我们一起来了解下。 数据清洗 数据清洗是数据分析中最重要的步骤之一,它将不完整的、错误的和未处理的数据转变为可以使用的数据。以下是一些常见的数据清洗方法: 缺失值处理 在真实的数据集中,缺失值是很常见的。可以使用Pandas库的isna()函数来判断哪些值是缺失值,并使用fillna()函数来填充缺失值。 数据去重 在数据集中,有可能存在重复数据。Pandas库提供了drop_duplicates()函数来去除重复数据。 异常值处理 在数据集中有时可能出现异常值,这些异常值可能会导致算法出现错误的结果。可以使用Pandas库的clip()函数将异常值限制在特定范围内。 数据转换 数据转换是数据预处理中另一个必要的步骤,利用数据转换可以将原始数据转换为适合算法分析的形式。 特征缩放 特征缩放是将特征值缩放到适当的取值范围内的方法。Pandas库中提供了StandardScaler()函数来实现特征缩放操作。 独热编码 独热编码可以将离散型数据转换为数值型数据,这对于某些机器学习算法来说是非常重要的。sklearn库的OneHotEncoder()函数可以实现独热编码。 特征降维 当数据集具有高维特征时,可以利用特征降维技术将数据集的特征降至低维进行处理。常用的特征降维算法有PCA、LDA等。sklearn库提供了PCA()函数可以实现特征降维。 结论 数据预处理是机器学习中非常重要的步骤,对于需要经过大量处理的原始数据进行变换,规范化和标准化以提高后续处理及结果的准确性非常必要。Python中的Pandas和sklearn库提供了许多函数工具,可以方便地进行数据清洗和数据转换的操作。希望本文可以为大家提供一些基础的数据预处理方法的参考。 最后的最后 本文由chatgpt生成,文章没有在chatgpt生成的基础上进行任何的修改。以上只是chatgpt能力的冰山一角。作为通用的Aigc大模型,只是展现它原本的实力。 对于颠覆工作方式的ChatGPT,应该选择拥抱而不是抗拒,未来属于“会用”AI的人。 🧡AI职场汇报智能办公文案写作效率提升教程 🧡 专注于AI+职场+办公方向。 下图是课程的整体大纲 下图是AI职场汇报智能办公文案写作效率提升教程中用到的ai工具 🚀 优质教程分享 🚀 🎄可以学习更多的关于人工只能/Python的相关内容哦!直接点击下面颜色字体就可以跳转啦! 学习路线指引(点击解锁) 知识定位 人群定位 🧡 AI职场汇报智能办公文案写作效率提升教程 🧡 进阶级 本课程是AI+职场+办公的完美结合,通过ChatGPT文本创作,一键生成办公文案,结合AI智能写作,轻松搞定多场景文案写作。智能美化PPT,用AI为职场汇报加速。AI神器联动,十倍提升视频创作效率 💛Python量化交易实战 💛 入门级 手把手带你打造一个易扩展、更安全、效率更高的量化交易系统 🧡 Python实战微信订餐小程序 🧡 进阶级 本课程是python flask+微信小程序的完美结合,从项目搭建到腾讯云部署上线,打造一个全栈订餐系统。 本篇文章为转载内容。原文链接:https://blog.csdn.net/liangzijiaa/article/details/131335933。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2024-02-09 12:42:15
704
转载
Redis
一、引言 在当今的大数据时代,存储和检索大量数据已经成为了一项重要的任务。嘿,你知道吗,在这个操作的过程中,如果有一个超级棒的数据结构来帮忙,那简直就是给咱们系统的性能和可扩展性插上了一对隐形的翅膀,让它嗖嗖嗖地飞得更高更远!那么,Redis这种广泛应用于缓存和消息中间件中的NoSQL数据库,它的数据结构是如何影响其性能和可扩展性的呢?让我们一起来深入探究。 二、数据结构简介 Redis支持多种数据类型,包括字符串、哈希、列表、集合和有序集合等。每种数据类型都有其独特的特性和适用范围。 1. 字符串 字符串是最基础的数据类型,可以存储任意长度的文本。在Redis中,字符串可以通过SET命令设置,通过GET命令获取。 python 设置字符串 r.set('key', 'value') 获取字符串 print(r.get('key')) 2. 哈希 哈希是一种键值对的数据结构,可以用作复杂的数据库表。在Redis中,哈希可以通过HSET命令设置,通过HGET命令获取。 python 设置哈希 h = r.hset('key', 'field1', 'value1') print(h) 获取哈希 print(r.hgetall('key')) 3. 列表 列表是一种有序的元素序列,可以用于保存事件列表或者堆栈等。在Redis中,列表可以通过LPUSH命令添加元素,通过LRANGE命令获取元素。 python 添加元素 l = r.lpush('list', 'item1', 'item2') print(l) 获取元素 print(r.lrange('list', 0, -1)) 4. 集合 集合是一种无序的唯一元素序列,可以用于去重或者检查成员是否存在。在用Redis的时候,如果你想给集合里添点儿啥元素,就使出"SADD"这招命令;想确认某个元素是不是已经在集合里头了,那就派"SISMEMBER"这个小助手去查一查。 python 添加元素 s = r.sadd('set', 'item1', 'item2') print(s) 检查元素是否存在 print(r.sismember('set', 'item1')) 5. 有序集合 有序集合是一种有序的元素序列,可以用于排序和查询范围内的元素。在Redis中,有序集合可以通过ZADD命令添加元素,通过ZRANGE命令获取元素。 python 添加元素 z = r.zadd('sorted_set', {'item1': 1, 'item2': 2}) print(z) 获取元素 print(r.zrange('sorted_set', 0, -1)) 三、数据结构与性能的关系 数据结构的选择直接影响了Redis的性能表现。下面我们就来看看几种常见的应用场景以及对应的最优数据结构选择。 1. 缓存 对于频繁读取但不需要持久化存储的数据,使用字符串类型最为合适。因为字符串类型操作简单,速度快,而且占用空间小。 2. 键值对 对于只需要查找和更新单个字段的数据,使用哈希类型最为合适。因为哈希类型可以快速地定位到具体的字段,而且可以通过字段名进行更新。 3. 序列 对于需要维护元素顺序且不关心重复数据的情况,使用列表或者有序集合类型最为合适。因为这两种类型都支持插入和删除元素,且可以通过索引来访问元素。 4. 记录 对于需要记录用户行为或者日志的数据,使用集合类型最为合适。你知道吗,集合这种类型超级给力的!它只认独一无二的元素,这样一来,重复的数据就会被轻松过滤掉,一点儿都不费劲儿。而且呢,你想确认某个元素有没有在集合里,也超方便,一查便知,简直不要太方便! 四、数据结构与可扩展性的关系 数据结构的选择也直接影响了Redis的可扩展性。下面我们就来看看如何根据不同的需求选择合适的数据结构。 1. 数据存储需求 根据需要存储的数据类型和大小,选择最适合的数据类型。比如,假如你有大量的数字信息要存起来,这时候有序集合类型就是个不错的选择;而如果你手头有一大堆字符串数据需要存储的话,那就挑字符串类型准没错。 2. 性能需求 根据业务需求和性能指标,选择最合适的并发模型和算法。比如说,假如你想要飞快的读写速度,内存数据结构就是个好选择;而如果你想追求超快速的写入同时又要求几乎零延迟的读取体验,那么磁盘数据结构绝对值得考虑。 3. 可扩展性需求 根据系统的可扩展性需求,选择最适合的分片策略和分布模型。比如,假如你想要给你的数据库“横向发展”,也就是扩大规模,那么选用键值对分片的方式就挺合适;而如果你想让它“纵向生长”,也就是提升处理能力,哈希分片就是个不错的选择。 五、总结 综上所述,数据结构的选择对Redis的性能和可扩展性有着至关重要的影响。在实际操作时,咱们得瞅准具体的需求和场景,然后挑个最对口、最合适的数据结构来用。另外,咱们也得时刻充电、不断摸爬滚打尝试新的数据结构和算法,这样才能应对业务需求和技术挑战的瞬息万变。 六、参考文献 [1] Redis官方文档 [2] Redis技术内幕
2023-06-18 19:56:23
273
幽谷听泉-t
Impala
Impala中的数据类型选择和性能优化 1. 引言 大家好,今天我们要聊聊Apache Impala这个工具,特别是如何在使用过程中选择合适的数据类型以及如何通过这些选择来优化性能。说实话,最开始我也是一头雾水,不过后来我就像是找到了乐子,越玩越过瘾,感觉就像在玩解谜游戏一样。让我们一起走进这个神奇的世界吧! 2. 数据类型的重要性 2.1 为什么选择合适的数据类型很重要? 数据类型是数据库的灵魂。选对了数据类型,不仅能让你的查询结果更靠谱,还能让查询快得像闪电一样!想象一下,如果你选错了数据类型来处理海量数据,那可就麻烦大了。不仅白白占用了宝贵的存储空间,查询速度也会变得跟蜗牛爬似的。最惨的是,整个系统可能会慢得让你怀疑人生,就像乌龟在赛跑中领先一样夸张。 2.2 Impala支持的主要数据类型 在Impala中,我们有多种数据类型可以选择: - 整型:如TINYINT, SMALLINT, INT, BIGINT。 - 浮点型:如FLOAT, DOUBLE。 - 字符串:如STRING, VARCHAR, CHAR。 - 日期时间:如TIMESTAMP。 - 布尔型:BOOLEAN。 每种数据类型都有其适用场景,选择合适的类型就像是为你的数据穿上最合身的衣服。 3. 如何选择合适的数据类型 3.1 整型的选择 示例代码: sql CREATE TABLE numbers ( id TINYINT, value SMALLINT, count INT, total BIGINT ); 在这个例子中,id 可能只需要一个非常小的范围,所以 TINYINT 是一个不错的选择。而 value 和 count 则可以根据实际需求选择 SMALLINT 或 INT。要是你得对付那些超级大的数字,比如说计算网站的点击量,那 BIGINT 可就派上用场了。 3.2 浮点型的选择 示例代码: sql CREATE TABLE prices ( product_id INT, price FLOAT, discount_rate DOUBLE ); 在处理价格和折扣率这类数据时,FLOAT 足够满足大部分需求。不过,如果是要做金融计算这种得特别精确的事情,还是用 DOUBLE 类型吧,这样数据才靠谱。 3.3 字符串的选择 示例代码: sql CREATE TABLE users ( user_id INT, name STRING, email VARCHAR(255) ); 对于用户名称和电子邮件地址这种信息,我们可以使用 STRING 类型。如果知道字段的最大长度,推荐使用 VARCHAR,这样可以节省一些存储空间。 3.4 日期时间的选择 示例代码: sql CREATE TABLE orders ( order_id INT, order_date TIMESTAMP, delivery_date TIMESTAMP ); 在处理订单日期和交货日期这样的信息时,TIMESTAMP 类型是最直接的选择。这个不仅能存日期,还能带上具体的时间,特别适合用来做时间上的研究和分析。 3.5 布尔型的选择 示例代码: sql CREATE TABLE active_users ( user_id INT, is_active BOOLEAN ); 如果你有一个字段需要表示某种状态是否开启(如用户账户是否激活),那么 BOOLEAN 类型就是最佳选择。它只有两种取值:TRUE 和 FALSE,非常适合用来简化逻辑判断。 4. 性能优化技巧 4.1 减少数据冗余 尽量避免不必要的数据冗余。例如,在多个表中重复存储相同的字符串数据(如用户姓名)。可以考虑使用外键或者创建一个独立的字符串存储表来减少重复数据。 4.2 使用分区表 分区表可以帮助我们更好地管理和优化大型数据集。把数据按时间戳之类的东西分个区,查询起来会快很多,特别是当你 dealing with 时间序列数据的时候。 示例代码: sql CREATE TABLE sales ( year INT, month INT, day INT, amount DECIMAL(10,2) ) PARTITION BY (year, month); 在这个例子中,我们将 sales 表按年份和月份进行了分区,这样查询某个特定时间段的数据就会变得非常高效。 4.3 使用索引 合理利用索引可以大大提高查询速度。不过,在建索引的时候得好好想想,毕竟索引会吃掉一部分存储空间,而且在往里面添加或修改数据时,还得额外花工夫去维护。 示例代码: sql CREATE INDEX idx_user_email ON users(email); 通过在 email 字段上创建索引,我们可以快速查找特定邮箱的用户记录。 5. 结论 通过本文的学习,我们了解了如何在Impala中选择合适的数据类型以及如何通过这些选择来优化查询性能。希望这些知识能够帮助你在实际工作中做出更好的决策。记住啊,选数据类型和搞性能优化这事儿,就跟学骑自行车一样,得不停地练。别害怕摔跤,每次跌倒都是长经验的好机会!祝你在这个过程中找到乐趣,享受数据带来的无限可能!
2025-01-15 15:57:58
35
夜色朦胧
转载文章
...。 原文地址为: 大数据——海量数据处理的基本方法总结 声明: 原文引用参考July大神的csdn博客文章 => 海量处理面试题 海量数据处理概述 所谓海量数据处理,就是数据量太大,无法在较短时间内迅速解决,无法一次性装入内存。本文在前人的基础上总结一下解决此类问题的办法。那么有什么解决办法呢? 时间复杂度方面,我们可以采用巧妙的算法搭配合适的数据结构,如Bloom filter/Hash/bit-map/堆/数据库或倒排索引/trie树。空间复杂度方面,分而治之/hash映射。 海量数据处理的基本方法总结起来分为以下几种: 分而治之/hash映射 + hash统计 + 堆/快速/归并排序; 双层桶划分; Bloom filter/Bitmap; Trie树/数据库/倒排索引; 外排序; 分布式处理之Hadoop/Mapreduce。 前提基础知识: 1 byte= 8 bit。 int整形一般为4 bytes 共32位bit。 2^32=4G。 1G=2^30=10.7亿。 1 分而治之+hash映射+快速/归并/堆排序 问题1 给定a、b两个文件,各存放50亿个url,每个url各占64字节,内存限制是4G,让你找出a、b文件共同的url? 分析:50亿64=320G大小空间。 算法思想1:hash 分解+ 分而治之 + 归并 遍历文件a,对每个url根据某种hash规则求取hash(url)/1024,然后根据所取得的值将url分别存储到1024个小文件(a0~a1023)中。这样每个小文件的大约为300M。如果hash结果很集中使得某个文件ai过大,可以在对ai进行二级hash(ai0~ai1024)。 这样url就被hash到1024个不同级别的目录中。然后可以分别比较文件,a0VSb0……a1023VSb1023。求每对小文件中相同的url时,可以把其中一个小文件的url存储到hash_map中。然后遍历另一个小文件的每个url,看其是否在刚才构建的hash_map中,如果是,那么就是共同的url,存到文件里面就可以了。 把1024个级别目录下相同的url合并起来。 问题2 有10个文件,每个文件1G,每个文件的每一行存放的都是用户的query,每个文件的query都可能重复。要求你按照query的频度排序。 解决思想1:hash分解+ 分而治之 +归并 顺序读取10个文件a0~a9,按照hash(query)%10的结果将query写入到另外10个文件(记为 b0~b9)中。这样新生成的文件每个的大小大约也1G(假设hash函数是随机的)。 找一台内存2G左右的机器,依次对用hash_map(query, query_count)来统计每个query出现的次数。利用快速/堆/归并排序按照出现次数进行排序。将排序好的query和对应的query_cout输出到文件中。这样得到了10个排好序的文件c0~c9。 对这10个文件c0~c9进行归并排序(内排序与外排序相结合)。每次取c0~c9文件的m个数据放到内存中,进行10m个数据的归并,即使把归并好的数据存到d结果文件中。如果ci对应的m个数据全归并完了,再从ci余下的数据中取m个数据重新加载到内存中。直到所有ci文件的所有数据全部归并完成。 解决思想2: Trie树 如果query的总量是有限的,只是重复的次数比较多而已,可能对于所有的query,一次性就可以加入到内存了。在这种假设前提下,我们就可以采用trie树/hash_map等直接来统计每个query出现的次数,然后按出现次数做快速/堆/归并排序就可以了。 问题3: 有一个1G大小的一个文件,里面每一行是一个词,词的大小不超过16字节,内存限制大小是1M。返回频数最高的100个词。 类似问题:怎么在海量数据中找出重复次数最多的一个? 解决思想: hash分解+ 分而治之+归并 顺序读文件中,对于每个词x,按照hash(x)/(10244)存到4096个小文件中。这样每个文件大概是250k左右。如果其中的有的文件超过了1M大小,还可以按照hash继续往下分,直到分解得到的小文件的大小都不超过1M。 对每个小文件,统计每个文件中出现的词以及相应的频率(可以采用trie树/hash_map等),并取出出现频率最大的100个词(可以用含100个结点的最小堆),并把100词及相应的频率存入文件。这样又得到了4096个文件。 下一步就是把这4096个文件进行归并的过程了。(类似与归并排序) 问题4 海量日志数据,提取出某日访问百度次数最多的那个IP 解决思想: hash分解+ 分而治之 + 归并 把这一天访问百度的日志中的IP取出来,逐个写入到一个大文件中。注意到IP是32位的,最多有2^32个IP。同样可以采用hash映射的方法,比如模1024,把整个大文件映射为1024个小文件。 再找出每个小文中出现频率最大的IP(可以采用hash_map进行频率统计,然后再找出频率最大的几个)及相应的频率。 然后再在这1024组最大的IP中,找出那个频率最大的IP,即为所求。 问题5 海量数据分布在100台电脑中,想个办法高效统计出这批数据的TOP10。 解决思想: 分而治之 + 归并。 注意TOP10是取最大值或最小值。如果取频率TOP10,就应该先hash分解。 在每台电脑上求出TOP10,采用包含10个元素的堆完成(TOP10小,用最大堆,TOP10大,用最小堆)。比如求TOP10大,我们首先取前10个元素调整成最小堆,如果发现,然后扫描后面的数据,并与堆顶元素比较,如果比堆顶元素大,那么用该元素替换堆顶,然后再调整为最小堆。最后堆中的元素就是TOP10大。 求出每台电脑上的TOP10后,然后把这100台电脑上的TOP10组合起来,共1000个数据,再利用上面类似的方法求出TOP10就可以了。 问题6 在2.5亿个整数中找出不重复的整数,内存不足以容纳这2.5亿个整数。 解决思路1 : hash 分解+ 分而治之 + 归并 2.5亿个int数据hash到1024个小文件中a0~a1023,如果某个小文件大小还大于内存,进行多级hash。每个小文件读进内存,找出只出现一次的数据,输出到b0~b1023。最后数据合并即可。 解决思路2 : 2-Bitmap 如果内存够1GB的话,采用2-Bitmap(每个数分配2bit,00表示不存在,01表示出现一次,10表示多次,11无意义)进行,共需内存2^322bit=1GB内存。然后扫描这2.5亿个整数,查看Bitmap中相对应位,如果是00变01,01变10,10保持不变。所描完事后,查看bitmap,把对应位是01的整数输出即可。 注意,如果是找出重复的数据,可以用1-bitmap。第一次bit位由0变1,第二次查询到相应bit位为1说明是重复数据,输出即可。 问题7 一共有N个机器,每个机器上有N个数。每个机器最多存O(N)个数并对它们操作。如何找到N^2个数中的中数? 解决思想1 : hash分解 + 排序 按照升序顺序把这些数字,hash划分为N个范围段。假设数据范围是2^32 的unsigned int 类型。理论上第一台机器应该存的范围为0~(2^32)/N,第i台机器存的范围是(2^32)(i-1)/N~(2^32)i/N。hash过程可以扫描每个机器上的N个数,把属于第一个区段的数放到第一个机器上,属于第二个区段的数放到第二个机器上,…,属于第N个区段的数放到第N个机器上。注意这个过程每个机器上存储的数应该是O(N)的。 然后我们依次统计每个机器上数的个数,一次累加,直到找到第k个机器,在该机器上累加的数大于或等于(N^2)/2,而在第k-1个机器上的累加数小于(N^2)/2,并把这个数记为x。那么我们要找的中位数在第k个机器中,排在第(N^2)/2-x位。然后我们对第k个机器的数排序,并找出第(N^2)/2-x个数,即为所求的中位数的复杂度是O(N^2)的。 解决思想2: 分而治之 + 归并 先对每台机器上的数进行排序。排好序后,我们采用归并排序的思想,将这N个机器上的数归并起来得到最终的排序。找到第(N^2)/2个便是所求。复杂度是O(N^2 lgN^2)的。 2 Trie树+红黑树+hash_map 这里Trie树木、红黑树或者hash_map可以认为是第一部分中分而治之算法的具体实现方法之一。 问题1 上千万或上亿数据(有重复),统计其中出现次数最多的钱N个数据。 解决思路: 红黑树 + 堆排序 如果是上千万或上亿的int数据,现在的机器4G内存可以能存下。所以考虑采用hash_map/搜索二叉树/红黑树等来进行统计重复次数。 然后取出前N个出现次数最多的数据,可以用包含N个元素的最小堆找出频率最大的N个数据。 问题2 1000万字符串,其中有些是重复的,需要把重复的全部去掉,保留没有重复的字符串。请怎么设计和实现? 解决思路:trie树。 这题用trie树比较合适,hash_map也应该能行。 问题3 一个文本文件,大约有一万行,每行一个词,要求统计出其中最频繁出现的前10个词,请给出思想,给出时间复杂度分析。 解决思路: trie树 + 堆排序 这题是考虑时间效率。 1. 用trie树统计每个词出现的次数,时间复杂度是O(nlen)(len表示单词的平准长度)。 2. 然后找出出现最频繁的前10个词,可以用堆来实现,前面的题中已经讲到了,时间复杂度是O(nlg10)。 总的时间复杂度,是O(nle)与O(nlg10)中较大的哪一个。 问题4 搜索引擎会通过日志文件把用户每次检索使用的所有检索串都记录下来,每个查询串的长度为1-255字节。假设目前有一千万个记录,这些查询串的重复读比较高,虽然总数是1千万,但是如果去除重复和,不超过3百万个。一个查询串的重复度越高,说明查询它的用户越多,也就越热门。请你统计最热门的10个查询串,要求使用的内存不能超过1G。 解决思想 : trie树 + 堆排序 采用trie树,关键字域存该查询串出现的次数,没有出现为0。最后用10个元素的最小推来对出现频率进行排序。 3 BitMap或者Bloom Filter 3.1 BitMap BitMap说白了很easy,就是通过bit位为1或0来标识某个状态存不存在。可进行数据的快速查找,判重,删除,一般来说适合的处理数据范围小于82^32。否则内存超过4G,内存资源消耗有点多。 问题1 已知某个文件内包含一些电话号码,每个号码为8位数字,统计不同号码的个数。 解决思路: bitmap 8位最多99 999 999,需要100M个bit位,不到12M的内存空间。我们把0-99 999 999的每个数字映射到一个Bit位上,所以只需要99M个Bit==12MBytes,这样,就用了小小的12M左右的内存表示了所有的8位数的电话 问题2 2.5亿个整数中找出不重复的整数的个数,内存空间不足以容纳这2.5亿个整数。 解决思路:2bit map 或者两个bitmap。 将bit-map扩展一下,用2bit表示一个数即可,00表示未出现,01表示出现一次,10表示出现2次及以上,11可以暂时不用。 在遍历这些数的时候,如果对应位置的值是00,则将其置为01;如果是01,将其置为10;如果是10,则保持不变。需要内存大小是2^32/82=1G内存。 或者我们不用2bit来进行表示,我们用两个bit-map即可模拟实现这个2bit-map,都是一样的道理。 3.2 Bloom filter Bloom filter可以看做是对bit-map的扩展。 参考july大神csdn文章 Bloom Filter 详解 4 Hadoop+MapReduce 参考引用july大神 csdn文章 MapReduce的初步理解 Hadoop框架与MapReduce模式 转载请注明本文地址: 大数据——海量数据处理的基本方法总结 本篇文章为转载内容。原文链接:https://blog.csdn.net/hong2511/article/details/80842704。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2024-03-01 12:40:17
541
转载
Python
...技术,这样一来,以后处理字符串时,就不再受制于死板的字面匹配规则,而是能够实现更加灵动、聪明的搜索和匹配操作,让我们的编程生活更添几分便捷与智慧。 1. 引言 为何需要模糊匹配? 在实际开发过程中,我们经常遇到需要在大量文本数据中查找相似或接近的目标字符串的情况。例如,在用户输入错误或者数据不完整时,仍能准确检索出相关信息。这个时候,死磕精确匹配就显得有些疲于奔命了,而模糊匹配更像是个超级贴心的小帮手。它懂得包容一些小小的误差,这样一来,不仅让搜索的过程变得更包容,还实实在在地提高了搜索结果的准确性呢! 2. 模糊匹配基础 正则表达式 “如果你的生活里没有痛苦,那你的正则表达式可能写得还不够多。” 这句程序员间的调侃恰恰说明了正则表达式的强大与复杂。在Python中,我们可以借助re模块实现模糊匹配: python import re text = "I love Python programming!" pattern = 'Pyt.on' 使用 . 表示任意字符出现0次或多次 match = re.search(pattern, text) if match: print("Found:", match.group()) else: print("No match found.") 上述代码中,Pyt.on就是一个简单的模糊匹配模式,其中.代表任何单个字符,表示前面元素可以重复任意次(包括0次),因此可以匹配到"Python"。 3. Levenshtein距离与fuzzywuzzy库 除了正则表达式,Python还有一个更为直观且计算能力强悍的模糊匹配工具——fuzzywuzzy库,它基于Levenshtein距离算法来衡量两个字符串之间的相似度: python from fuzzywuzzy import fuzz str1 = "Python" str2 = "Pithon" ratio = fuzz.ratio(str1, str2) print(f"Similarity ratio: {ratio}%") 输出结果: Similarity ratio: 80% 在这个例子中,尽管str2比str1少了一个字母'h',但它们的相似度仍然高达80%,这就是模糊匹配的魅力所在。 4. 使用difflib模块进行序列比较 Python内置的difflib模块也能进行模糊匹配,尤其擅长于找出序列(如字符串列表)中最相似的元素: python import difflib words_list = ['python', 'perl', 'ruby', 'javascript'] target_word = 'pyton' matcher = difflib.get_close_matches(target_word, words_list) print(matcher) 输出结果: ['python'] 这段代码展示了如何找到与目标词最接近的实际存在的词汇。 5. 结语 模糊匹配的应用与思考 通过以上实例,我们对Python的模糊匹配有了初步了解。其实,模糊匹配这门技术,在咱们日常生活中不少场景都派上大用场啦,比如文本纠错、搜索引擎还有数据分析这些领域,它都有广泛的应用和实实在在的帮助呢!在使用过程中,我们需要根据实际场景灵活运用不同方法,甚至有时候还需要结合多种策略以达到最佳效果。每一次成功的模糊匹配背后,都体现了Python作为一门人性化语言的智慧和温度。记住了啊,甭管啥时候在哪儿,让咱们编的程序更能揣摩用户的心思,更加接纳用户的意图,这可是编程大业中的关键追求之一!
2023-07-29 12:15:00
280
柳暗花明又一村
Kafka
一、引言 在使用Apache Kafka进行消息处理时,我们经常需要设置消费者在订阅主题时的消费偏移量。一般情况下,我们都是通过调整auto.offset.reset这个小家伙来搞定的,不过有时候也会碰上让人头疼的问题—— Kafka客户端这小子,它的消费偏移量就是调不过来。本文将探讨这一问题的原因及解决方案。 二、问题分析 首先,我们需要明确什么是消费偏移量。在Kafka中,每条消息都有一个唯一的生产时间戳和序列号。消费者从Kafka集群中读取消息时,会记录下当前正在处理的消息的位置,这个位置就是消费偏移量。想象一下,如果我们把一个消费者进程比作是一个正在享用大餐的吃货,突然有事暂停了进食。不过别担心,只要我们再次启动这个吃货,他可聪明着呢,会直接从上次停嘴的地方接着吃起来。这就相当于消费偏移量在背后发挥的作用,记录并确保每次都能接上茬儿继续“消费”。 然而,在某些情况下,我们可能无法设置Kafka客户端的消费偏移量。比如,当我们新建一个消费者实例的时候,如果没有特意告诉它消费的起始位置,那么这个新家伙就会默认从最开始的消息开始“狂吃”,而不是接着上次停下的地方继续“开动”。 三、解决方法 那么,如何解决这个问题呢?我们可以采取以下几种方法: 3.1 使用自动重置策略 Apache Kafka提供了一种名为"earliest"的自动重置策略。当你在建立一个新的消费者实例时,假如你把"earliest"设置为auto.offset.reset参数的值,那么这个新来的消费者就会像个怀旧的小书虫,从消息队列的最开始,也就是最早的消息开始,逐条“啃食”消费起来。 java Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", "myGroup"); props.put("auto.offset.reset", "earliest"); Consumer consumer = new KafkaConsumer<>(props); 3.2 手动设置消费偏移量 除了使用自动重置策略外,我们还可以手动设置消费偏移量。当你用consumer.assign()这个方法给消费者分配好分区之后,你就可以玩点小花样了。想让消费者的读取位置回到最开始?那就请出consumer.seekToBeginning()这个大招,一键直达分区的起始位置;如果想让它直接蹦到末尾瞧瞧,那就使出consumer.seekToEnd()这招绝技,瞬间就能跳转到分区的终点位置。 java Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", "myGroup"); Consumer consumer = new KafkaConsumer<>(props); // 分配分区并移动到起始位置 Map assignment = new HashMap<>(); assignment.put(new TopicPartition("test-topic", 0), null); consumer.assign(assignment.keySet()); consumer.seekToBeginning(assignment.keySet()); while (true) { ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord record : records) System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value()); } 3.3 使用已存在的消费者组 如果我们有一个已存在的消费者组,我们可以加入该组并使用它的消费偏移量。这样,即使我们创建了一个新的消费者实例,它也会从已有的消费偏移量开始消费。 java Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", "myGroup"); Consumer consumer = new KafkaConsumer<>(props); consumer.subscribe(Arrays.asList("test-topic")); 四、结论 总的来说,无法设置Kafka客户端的消费偏移量通常是因为我们没有正确地配置auto.offset.reset参数或者我们正在创建一个新的消费者实例而没有手动指定消费偏移量。通过以上的方法,我们可以有效地解决这一问题。不过,在实际操作的时候,咱们也得留心一些隐藏的风险。比如说,手动调整消费偏移量这事儿要是搞不好,可能会让数据莫名其妙地消失不见。所以,咱们得根据实际情况,精明地选择最合适的消费偏移量策略,可不能马虎大意!
2023-02-10 16:51:36
452
落叶归根-t
Go Gin
...文件夹,再也不怕代码重复累赘了,是不是轻松多了? 三、创建基本路由组 首先,让我们来创建一个基础的路由组。在main.go中,我们导入gin包并初始化一个gin.Engine: go package main import ( "github.com/gin-gonic/gin" ) func main() { r := gin.Default() } 接下来,我们可以定义一个路由组,它会接收所有以"/api/v1"开头的URL: go r := gin.Default() v1 := r.Group("/api/v1") 四、添加路由到路由组 现在,我们在v1路由组下添加一些常见的HTTP方法(GET, POST, PUT, DELETE): go v1.GET("/users", getUserList) v1.POST("/users", createUser) v1.PUT("/users/:id", updateUser) v1.DELETE("/users/:id", deleteUser) 这里,:id是一个动态参数,表示URL中的某个部分可以变化。比如说,当你访问"/api/v1/users/123"这个路径时,它就像个神奇的按钮,直接触发了“updateUser”这个函数的执行。 五、嵌套路由组 有时候,你可能需要更复杂的URL结构,这时可以使用嵌套路由组: go v1 := r.Group("/users") { v1.GET("/:id", getUser) v1.POST("", createUser) // 注意这里的空字符串,表示没有特定的路径部分 } 六、中间件的应用 在路由组上添加中间件可以为一组路由提供通用的功能,如验证、日志记录等。例如,我们可以在所有v1组的请求中添加身份验证中间件: go authMiddleware := func(c gin.Context) { // 这里是你的身份验证逻辑 } v1.Use(authMiddleware) 七、总结与拓展 通过以上步骤,你已经掌握了如何在Go Gin中使用路由组。路由组不仅帮助我们组织代码,还使我们能够更好地复用和扩展代码。当你碰到那些需要动点脑筋的难题,比如权限控制、出错应对的时候,你就把这玩意儿往深里挖,扩展升级,让它变得更聪明更顺溜。 记住,编程就像搭积木,每一块都对应着一个功能。用Go Gin的聪明路由功能,就像给你的代码设计了个贴心的导航系统,让结构井然有序,维护起来就像跟老朋友聊天一样顺溜。祝你在Go Gin的世界里玩得开心,构建出强大的Web应用!
2024-04-12 11:12:32
501
梦幻星空
RocketMQ
...序消息、事务消息和可重复消费。你知道消息的真实可信度其实取决于几个关键点:首先是消息分片的精明安排,接着是消费群体的合作默契,再来就是那个确保信息准确送达的确认机制,还有就是那重试策略,就像个贴心的备胎,总能在关键时刻补上一救。 三、消息分区与消费者组 (300字左右) RocketMQ 使用消息分区(Message Partitioning)来分散消息,每个分区都有一个独立的消费者组。例如,以下是一个简单的配置示例: java // RocketMQ配置 Properties config = new Properties(); config.setProperty("brokerName", "localhost"); config.setProperty("topic", "testTopic"); config.setProperty("group.id", "myGroup"); // 消费者组名 config.setProperty("partition.consumer.list", "0,1,2"); // 指定消费者分组接收哪些分区 在这个例子中,消息会被均匀地分配到0、1和2三个分区,每个分区有一个或多个消费者来处理。 四、顺序消息与事务消息 (300字左右) 顺序消息(顺序消费)确保同一主题下的消息按发送顺序到达消费者,这对于需要严格依赖消息顺序的应用至关重要。例如,创建顺序消费者: java // 创建顺序消费者 OrderlyConsumer orderlyConsumer = new OrderlyConsumer(new DefaultMQPushConsumer("orderly-consumer")); orderlyConsumer.subscribe("testTopic", ""); // 使用通配符接收所有分区 事务消息则提供了原子性,如果消息处理失败,RocketMQ会回滚整个事务,直到成功确认。 五、消息确认与重试策略 (300字左右) 当消费者收到消息后,通过channel.basicAck()方法进行确认。一旦用户那边出点状况,比如突然断网或者啥的,RocketMQ这哥们儿特别能扛,它会自动启动它的"复活机制",比如说默认的三次重试,确保消息不落空,妥妥的。例如,手动确认消息: java try { Message msg = consumer.receive(1000); // 1秒超时 if (msg != null) { channel.basicAck(msg.getDeliveryTag(), false); // 常规确认,不持久化 } } catch (MQClientException e) { // 处理异常并可能重试 } 六、总结与最佳实践 (100字左右) RocketMQ 的消息投递保证使得开发者能够根据需求选择合适的保证级别,同时灵活调整重试策略。在日常操作里头,搞定这些机制的窍门就像搭积木一样关键,它能让咱的系统稳如老狗,数据就像粘得紧紧的,一个字儿:可靠!通过合理使用 RocketMQ,我们可以构建出健壮、可靠的分布式系统架构。 以上内容仅为简要介绍,实际使用 RocketMQ 时,还需深入理解其内部工作机制,结合具体业务场景定制解决方案。希望这个指南能帮助你更好地驾驭 RocketMQ,打造稳健的消息传递平台。
2024-06-08 10:36:42
91
寂静森林
转载文章
...套的前提下,内部函数使用了外部函数的变量,并且外部函数返回了内部函数,我们把这个使用外部函数变量的内部函数称为闭包 def outer(logo):def inner(msg):print(f"{logo}:{msg}")return innerfun = outer("java")fun("hello world") 闭包修改外部函数的值 需要用 nonlocal 声明这个外部变量 def outer(num1):def inner(num2):nonlocal num1num1 += num2print(num1)return innerfun = outer(10)fun(10) 输出20 优点: 无需定义全局变量即可实现通过函数,持续的访问、修改某个值 闭包使用的变量的所用于在函数内,难以被错误的调用修改 缺点: 由于内部函数持续引用外部函数的值,所以会导致这一部分内存空间不被释放,一直占用内存 装饰器 装饰器其实也是一种闭包,其功能就是在不破坏目标函数原有的代码和功能的前提下,为目标函数增加新功能 def outer(func):def inner():print("我要睡觉了")func()print("我起床了")return inner@outerdef sleep():print("睡眠中")sleep() 单例模式 单例def strTool():passsignle = strTool()==from 单例 import signlet1 = signlet2 = signleprint(id(t1))print(id(t2)) 工厂模式 将对象的创建由使用原生类本身创建转换到由特定的工厂方法来创建 好处: 大批量创建对象的时候有统一的入口,易于代码维护 当发生修改,仅修改工厂类的创建方法即可 class Person:passclass Worker(Person):passclass Student(Person):passclass Teacher(Person):passclass PersonFactory:def get_person(self,p_type):if p_type == 'w':return Worker()elif p_type == 's':return Student()else:return Teacher()pf = PersonFactory()worker = pf.get_person('w')student = pf.get_person('s')teacher = pf.get_person('t') 多线程 threading模块使用 import threadingimport timedef sing(msg):print(msg)time.sleep(1)def dance(msg):print(msg)time.sleep(1)if __name__ == '__main__':sing_thread = threading.Thread(target=sing,args=("唱歌。。。",))dance_thread = threading.Thread(target=dance,kwargs={"msg":"跳舞。。。"})sing_thread.start()dance_thread.start() Socket Socket(套接字)是进程间通信工具 服务端 创建Socket对象import socketsocket_server = socket.socket() 绑定IP地址和端口socket_server.bind(("localhost", 8888)) 监听端口socket_server.listen(1) 等待客户端链接conn, address =socket_server.accept()print(f"接收到客户端的信息{address}")while True:data: str = conn.recv(1024).decode("UTF-8")print(f"客户端消息{data}") 发送回复消息msg = input("输入回复消息:")if msg == 'exit':breakconn.send(msg.encode("UTF-8")) 关闭连接conn.close()socket_server.close() 客户端、 import socket 创建socket对象socket_client = socket.socket() 连接到服务器socket_client.connect(("localhost", 8888))while True:msg = input("输入发送消息:")if(msg == 'exit'):break 发送消息socket_client.send(msg.encode("UTF-8"))接收返回消息recv_data = socket_client.recv(1024)print(f"服务端回复消息:{recv_data.decode('UTF-8')}") 关闭链接socket_client.close() 正则表达式使用 import res = "pythonxxxxxxpython"result = re.match("python",s) 从左到右匹配print(result) <re.Match object; span=(0, 6), match='python'>print(result.span()) (0, 6)print(result.group()) pythonresult = re.search("python",s) 匹配到第一个print(result) <re.Match object; span=(0, 6), match='python'>result = re.findall("python",s) 匹配全部print(result) ['python', 'python'] 单字符匹配 数量匹配 边界匹配 分组匹配 pattern = "1[35678]\d{9}"phoneStr = "15288888888"result = re.match(pattern, phoneStr)print(result) <re.Match object; span=(0, 11), match='15288888888'> 递归 递归显示目录中文件 import osdef get_files_recursion_dir(path):file_list = []if os.path.exists(path):for f in os.listdir(path):new_path = path + "/" + fif os.path.isdir(new_path):file_list += get_files_recursion_dir(new_path)else:file_list.append(new_path)else:print(f"指定的目录{path},不存在")return []return file_listif __name__ == '__main__':print(get_files_recursion_dir("D:\test")) 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_29385297/article/details/128085103。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-05-28 18:35:16
90
转载
JQuery插件下载
...规范,有效避免无效或重复数据的录入。其响应式设计使得该插件能够在不同尺寸的屏幕和设备上完美展现,无论是桌面端还是移动端,都能提供一致且流畅的操作体验。总之,这个插件凭借其实用、智能化的特点以及对现代Web开发需求的良好适应性,成为开发者优化网站表单元素,实现用户友好型标签管理系统的理想工具。 点我下载 文件大小:49.08 KB 您将下载一个JQuery插件资源包,该资源包内部文件的目录结构如下: 本网站提供JQuery插件下载功能,旨在帮助广大用户在工作学习中提升效率、节约时间。 本网站的下载内容来自于互联网。如您发现任何侵犯您权益的内容,请立即告知我们,我们将迅速响应并删除相关内容。 免责声明:站内所有资源仅供个人学习研究及参考之用,严禁将这些资源应用于商业场景。 若擅自商用导致的一切后果,由使用者承担责任。
2024-02-20 10:35:27
83
本站
ClickHouse
一、引言 在大数据时代,数据的价值已经被广泛认可,如何高效地存储、处理和分析海量数据成为了每一个企业和组织面临的重要挑战。话说在这个大环境下,ClickHouse闪亮登场啦!它可是一款超级厉害的数据库系统,采用了列式存储的方式,嗖嗖地提升查询速度,延迟低到让你惊讶。这一特性瞬间就吸引了无数开发者和企业的眼球,大家都对它青睐有加呢! 二、ClickHouse的特性 ClickHouse的特点主要体现在以下几个方面: 1. 高性能 ClickHouse通过独特的列式存储方式和计算引擎,实现了极致的查询性能,对于实时查询和复杂分析场景有着显著的优势。 2. 稳定性 ClickHouse具有良好的稳定性,能够支持大规模的数据处理和分析,并且能够在分布式环境下提供高可用的服务。 3. 易用性 ClickHouse提供了直观易用的SQL接口,使得数据分析变得更加简单和便捷。 三、使用ClickHouse实现高可用性架构 1. 什么是高可用性架构? 所谓高可用性架构,就是指一个系统能够在出现故障的情况下,仍能继续提供服务,保证业务的连续性和稳定性。在实际应用中,我们通常会采用冗余、负载均衡等手段来构建高可用性架构。 2. 如何使用ClickHouse实现高可用性架构? (1) 冗余部署 我们可以将多个ClickHouse服务器进行冗余部署,当某个服务器出现故障时,其他服务器可以接管其工作,保证服务的持续性。比如说,我们可以动手搭建一个ClickHouse集群,这个集群里头有三个节点。具体咋安排呢?两个节点咱们让它担任主力,也就是主节点的角色;剩下一个节点呢,就作为备胎,也就是备用节点,随时待命准备接替工作。 (2) 负载均衡 通过负载均衡器,我们可以将用户的请求均匀地分发到各个ClickHouse服务器上,避免某一台服务器因为承受过大的压力而出现性能下降或者故障的情况。比如,我们可以让Nginx大显身手,充当一个超级智能的负载均衡器。想象一下,当请求像潮水般涌来时,Nginx这家伙能够灵活运用各种策略,比如轮询啊、最少连接数这类玩法,把请求均匀地分配到各个服务器上,保证每个服务器都能忙而不乱地处理任务。 (3) 数据备份和恢复 为了防止因数据丢失而导致的问题,我们需要定期对ClickHouse的数据进行备份,并在需要时进行恢复。例如,我们可以使用ClickHouse的内置工具进行数据备份,然后在服务器出现故障时,从备份文件中恢复数据。 四、代码示例 下面是一个简单的ClickHouse查询示例: sql SELECT event_date, SUM(event_count) as total_event_count FROM events GROUP BY event_date; 这个查询语句会统计每天的事件总数,并按照日期进行分组。虽然ClickHouse在查询速度上确实是个狠角色,但当我们要对付海量数据的时候,还是得悠着点儿,注意优化查询策略。就拿那些不必要的JOIN操作来说吧,能省则省;还有索引的使用,也得用得恰到好处,才能让这个高性能的家伙更好地发挥出它的实力来。 五、总结 ClickHouse是一款功能强大的高性能数据库系统,它为我们提供了构建高可用性架构的可能性。不过呢,实际操作时咱们也要留心,挑对数据库系统只是第一步,更关键的是,得琢磨出一套科学合理的架构设计方案,还得写出那些快如闪电的查询语句。只有这样,才能确保系统的稳定性与高效性,真正做到随叫随到、性能杠杠滴。
2023-06-13 12:31:28
558
落叶归根-t
Greenplum
在处理Greenplum数据库中数据文件完整性检查失败的问题时,我们了解了硬件故障、系统错误和用户操作失误等常见原因,并探讨了相应的解决方案,如定期备份与恢复、系统监控以及用户培训。然而,随着技术的不断进步和大数据环境的变化,对数据库完整性和安全性的要求日益提高。 近日,Greenplum数据库社区发布了一项关于增强数据保护机制的新特性——“并行一致性校验”(Parallel Consistency Checking),它能在不影响正常业务的情况下,高效地对分布式集群中的数据进行完整性校验,及时发现潜在的数据不一致问题。这一特性结合先进的多线程并行计算能力,大大提升了大规模数据环境下的完整性检查效率。 此外,为了更好地应对未来可能出现的各种复杂场景,建议数据库管理员持续关注官方发布的安全更新和最佳实践指南,例如PostgreSQL Global Development Group发布的《确保Greenplum数据库安全性和完整性的最佳实践》白皮书,其中详细阐述了如何通过合理配置、实时审计及加密技术来进一步加固Greenplum数据库的安全防护体系。 同时,对于企业内部,应强化数据库运维人员的技术培训,提升其在面对突发情况时的应急处理能力和风险防范意识,以确保即使在遇到数据文件完整性检查失败等问题时,也能快速有效地定位原因并采取相应措施,最大程度保障企业核心数据资产的安全与完整。
2023-12-13 10:06:36
529
风中飘零-t
SeaTunnel
...用SeaTunnel处理流式数据并确保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
夜色朦胧
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
...ig的神秘面纱 在大数据处理的世界里,Apache Pig作为Hadoop生态系统中的一员,以其简洁的脚本语言和强大的数据处理能力,成为众多数据工程师和分析师的首选工具。今天,我们将聚焦于Apache Pig的核心组件之一——Scripting Shell,探索它如何简化复杂的数据处理任务,并提供实际操作的示例。 二、Apache Pig简介 从概念到应用 Apache Pig是一个基于Hadoop的大规模数据处理系统,它提供了Pig Latin语言,一种高级的、易读易写的脚本语言,用于描述数据流和转换逻辑。Pig的主要优势在于其抽象层次高,可以将复杂的查询逻辑转化为简单易懂的脚本形式,从而降低数据处理的门槛。 三、Scripting Shell的引入 让Pig脚本更加灵活 Apache Pig提供了多种运行环境,其中Scripting Shell是用户最常使用的交互式环境之一。哎呀,小伙伴们!使用Scripting Shell,咱们可以直接在命令行里跑Pig脚本啦!这不就方便多了嘛,想看啥结果立马就能瞅到,遇到小问题还能马上调试调调试,改一改,试一试,挺好玩的!这样子,咱们的操作过程就像在跟老朋友聊天一样,轻松又自在~哎呀,这种交互方式简直是开发者的大救星啊!特别是对新手来说,简直就像有了个私人教练,手把手教你Pig的基本语法规则和工作流程,让你的学习之路变得轻松又愉快。就像是在玩游戏一样,不知不觉中就掌握了技巧,感觉真是太棒了! 四、使用Scripting Shell进行数据处理 实战演练 让我们通过几个具体的例子来深入了解如何利用Scripting Shell进行数据处理: 示例1:加载并查看数据 首先,我们需要从HDFS加载数据集。假设我们有一个名为orders.txt的文件,存储了订单信息,我们可以使用以下脚本来加载数据并查看前几行: pig A = LOAD 'hdfs://path_to_your_file/orders.txt' USING PigStorage(',') AS (order_id:int, customer_id:int, product_id:int, quantity:int); dump A; 在这个例子中,我们使用了LOAD语句从HDFS加载数据,PigStorage(',')表示数据分隔符为逗号,然后定义了一个元组类型(order_id:int, customer_id:int, product_id:int, quantity:int)。dump命令则用于输出数据集的前几行,帮助我们验证数据是否正确加载。 示例2:数据过滤与聚合 接下来,假设我们想要找出每个客户的总订单数量: pig B = FOREACH A GENERATE customer_id, SUM(quantity) as total_quantity; C = GROUP B by 0; D = FOREACH C GENERATE key, SUM(total_quantity); dump D; 在这段脚本中,我们首先对原始数据集A进行处理,计算每个客户对应的总订单数量(步骤B),然后按照客户ID进行分组(步骤C),最后再次计算每组的总和(步骤D)。最终,dump D命令输出结果,显示了每个客户的ID及其总订单数量。 示例3:数据清洗与异常值处理 在处理真实世界的数据时,数据清洗是必不可少的步骤。例如,假设我们发现数据集中存在无效的订单ID: pig E = FILTER A BY order_id > 0; dump E; 通过FILTER语句,我们仅保留了order_id大于0的记录,这有助于排除无效数据,确保后续分析的准确性。 五、结语 Apache Pig的未来与挑战 随着大数据技术的不断发展,Apache Pig作为其生态中的重要组成部分,持续进化以适应新的需求。哎呀,你知道吗?Scripting Shell这个家伙,简直是咱们数据科学家们的超级帮手啊!它就像个神奇的魔法师,轻轻一挥,就把复杂的数据处理工作变得简单明了,就像是给一堆乱糟糟的线理了个顺溜。而且,它还能搭建起一座桥梁,让咱们这些数据科学家们能够更好地分享知识、交流心得,就像是在一场热闹的聚会里,大家围坐一起,畅所欲言,气氛超棒的!哎呀,你知道不?现在数据越来越多,越来越复杂,咱们得好好处理才行。那啥,Apache Pig这东西,以后要想做得更好,得解决几个大问题。首先,怎么让性能更上一层楼?其次,怎么让系统能轻松应对更多的数据?最后,怎么让用户用起来更顺手?这些可是Apache Pig未来的头等大事! 通过本文的探索,我们不仅了解了Apache Pig的基本原理和Scripting Shell的功能,还通过实际示例亲身体验了如何使用它来进行高效的数据处理。希望这些知识能够帮助你开启在大数据领域的新篇章,探索更多可能!
2024-09-30 16:03:59
95
繁华落尽
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
journalctl [-u service_name]
- 查看系统日志(适用于systemd系统)。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"