前端技术
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
[pytesseractimage_to_...]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Spark
...gs: Array[String]) { val conf = new SparkConf().setAppName("Word Count").setMaster("local") val sc = new SparkContext(conf) val textFile = sc.textFile("file:///path/to/your/textfile.txt") val counts = textFile.flatMap(line => line.split(" ")) .map(word => (word, 1)) .reduceByKey(_ + _) counts.saveAsTextFile("output") sc.stop() } } 四、错误日志分析 内存溢出问题 在实际运行上述应用时,如果输入文本文件过大,可能会导致内存溢出错误。日志文件中可能会出现类似以下的信息: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 37.0 failed 1 times, most recent failure: Lost task 0.3 in stage 37.0 (TID 208, localhost): java.lang.OutOfMemoryError: Java heap space 这段日志信息清晰地指出错误原因(OutOfMemoryError: Java heap space),并提供了关键细节,包括任务编号、所在节点以及错误类型。针对这一问题,可以通过增加Spark集群的内存资源或者优化数据处理逻辑来解决。 五、调试策略与最佳实践 1. 使用日志级别 调整日志级别(如INFO、DEBUG)可以帮助开发者在日志中获取更多详细信息。 2. 定期检查日志 通过自动化工具定期检查日志文件,可以及时发现潜在问题。 3. 利用Spark UI Spark自带的Web UI提供了详细的作业监控界面,直观显示任务状态和性能指标。 4. 错误重试机制 合理配置Spark任务的重试策略,避免因一次失败而影响整体进程。 5. 性能监控工具 集成性能监控工具(如Prometheus、Grafana)有助于实时监控系统性能,预防内存泄漏等严重问题。 六、总结与展望 日志记录是Spark应用程序开发和维护过程中的关键环节。哎呀,你知道吗?程序员们在遇到bug(小错误)的时候,那可是得使出浑身解数了!他们可不是对着电脑屏幕发呆,而是会仔细地分析问题,就像侦探破案一样。找到问题的源头后,他们就开始了他们的“调试大作战”,就像是医生给病人开药一样精准。通过这些努力,他们能优化代码,让程序跑得更顺畅,就像给汽车加了润滑剂,不仅跑得快,还稳当当的。这样,我们的应用就能更加可靠,用户用起来也更舒心啦!哎呀,你懂的,随着咱们每天产生的数据就像自来水一样哗哗流,那处理这些数据的大数据工具就得越来越厉害才行。特别是那些记录我们操作痕迹的日志管理系统,不仅要快得跟闪电一样,操作起来还得像玩手机游戏一样简单,最好还能自己动脑筋分析出点啥有价值的信息来。这样,未来日志记录这事儿就不仅仅是记录,还能帮我们找到问题、优化流程,简直就是一大神器嘛!所以,你看,这发展方向就是越来越智能、好用、高效,让科技真正服务于人,而不是让人被科技牵着鼻子走。 --- 通过本文的探讨,我们不仅学习了如何理解和利用Spark的日志信息来诊断问题,还了解了一些实用的调试技巧和最佳实践。希望这些内容能帮助你更有效地管理你的Spark应用程序,确保其在复杂的数据处理场景下稳定运行。
2024-09-07 16:03:18
141
秋水共长天一色
转载文章
...MySQL服务器实例配置文件 ---------------------------------------------------------------------- Generated by the MySQL Server Instance Configuration Wizard 由MySQL服务器实例配置向导生成 Installation Instructions 安装说明 ---------------------------------------------------------------------- On Linux you can copy this file to /etc/my.cnf to set global options, mysql-data-dir/my.cnf to set server-specific options (@localstatedir@ for this installation) or to ~/.my.cnf to set user-specific options. 在Linux上,您可以将该文件复制到/etc/my.cnf来设置全局选项,mysql-data-dir/my.cnf来设置特定于服务器的选项(此安装的@localstatedir@),或者~/.my.cnf来设置特定于用户的选项。 On Windows you should keep this file in the installation directory of your server (e.g. C:\Program Files\MySQL\MySQL Server X.Y). To make sure the server reads the config file use the startup option "--defaults-file". 在Windows上你应该保持这个文件在服务器的安装目录(例如C:\Program Files\MySQL\MySQL服务器X.Y)。要确保服务器读取配置文件,请使用启动选项“——default -file”。 To run the server from the command line, execute this in a command line shell, e.g. mysqld --defaults-file="C:\Program Files\MySQL\MySQL Server X.Y\my.ini" 要从命令行运行服务器,请在命令行shell中执行,例如mysqld——default -file="C:\Program Files\MySQL\MySQL server X.Y\my.ini" To install the server as a Windows service manually, execute this in a command line shell, e.g. mysqld --install MySQLXY --defaults-file="C:\Program Files\MySQL\MySQL Server X.Y\my.ini" 要手动将服务器安装为Windows服务,请在命令行shell中执行此操作,例如mysqld——install MySQLXY——default -file="C:\Program Files\MySQL\MySQL server X.Y\my.ini" And then execute this in a command line shell to start the server, e.g. net start MySQLXY 然后在命令行shell中执行这个命令来启动服务器,例如net start MySQLXY Guidelines for editing this file编辑此文件的指南 ---------------------------------------------------------------------- In this file, you can use all long options that the program supports. If you want to know the options a program supports, start the program with the "--help" option. 在这个文件中,您可以使用程序支持的所有长选项。如果您想知道程序支持的选项,请使用“——help”选项启动程序。 More detailed information about the individual options can also be found in the manual. For advice on how to change settings please see https://dev.mysql.com/doc/refman/8.0/en/server-configuration-defaults.html 有关各个选项的更详细信息也可以在手册中找到。有关如何更改设置的建议,请参见https://dev.mysql.com/doc/refman/8.0/en/server-configuration-defaults.html CLIENT SECTION 客户端部分 ---------------------------------------------------------------------- The following options will be read by MySQL client applications. Note that only client applications shipped by MySQL are guaranteed to read this section. If you want your own MySQL client program to honor these values, you need to specify it as an option during the MySQL client library initialization. MySQL客户机应用程序将读取以下选项。注意,只有MySQL提供的客户端应用程序才能阅读本节。如果您希望自己的MySQL客户机程序遵守这些值,您需要在初始化MySQL客户机库时将其指定为一个选项。 [client] pipe= socket=MYSQL port=3306 [mysql] no-beep default-character-set= SERVER SECTION 服务器部分 ---------------------------------------------------------------------- The following options will be read by the MySQL Server. Make sure that you have installed the server correctly (see above) so it reads this file. MySQL服务器将读取以下选项。确保您已经正确安装了服务器(参见上面),以便它读取这个文件。 server_type=3 [mysqld] The next three options are mutually exclusive to SERVER_PORT below. 下面的三个选项对SERVER_PORT是互斥的。skip-networking enable-named-pipe 共享内存 skip-networking enable-named-pipe shared-memory shared-memory-base-name=MYSQL The Pipe the MySQL Server will use socket=MYSQL The TCP/IP Port the MySQL Server will listen on port=3306 Path to installation directory. All paths are usually resolved relative to this. basedir="C:/Program Files/MySQL/MySQL Server 8.0/" Path to the database root datadir=C:/ProgramData/MySQL/MySQL Server 8.0/Data The default character set that will be used when a new schema or table is created and no character set is defined 创建新模式或表时使用的默认字符集,并且没有定义字符集 character-set-server= The default authentication plugin to be used when connecting to the server 连接到服务器时使用的默认身份验证插件 default_authentication_plugin=caching_sha2_password The default storage engine that will be used when create new tables when 当创建新表时将使用的默认存储引擎 default-storage-engine=INNODB Set the SQL mode to strict 将SQL模式设置为strict sql-mode="STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION" General and Slow logging. 一般和缓慢的日志。 log-output=NONE general-log=0 general_log_file="DESKTOP-NF9QETB.log" slow-query-log=0 slow_query_log_file="DESKTOP-NF9QETB-slow.log" long_query_time=10 Binary Logging. 二进制日志。 log-bin Error Logging. 错误日志记录。 log-error="DESKTOP-NF9QETB.err" Server Id. server-id=1 Indicates how table and database names are stored on disk and used in MySQL. 指示表名和数据库名如何存储在磁盘上并在MySQL中使用。 Value = 0: Table and database names are stored on disk using the lettercase specified in the CREATE TABLE or CREATE DATABASE statement. Name comparisons are case sensitive. You should not set this variable to 0 if you are running MySQL on a system that has case-insensitive file names (such as Windows or macOS). Value = 0:表名和数据库名使用CREATE Table或CREATE database语句中指定的lettercase存储在磁盘上。名称比较区分大小写。如果您在一个具有不区分大小写文件名(如Windows或macOS)的系统上运行MySQL,则不应将该变量设置为0。 Value = 1: Table names are stored in lowercase on disk and name comparisons are not case-sensitive. MySQL converts all table names to lowercase on storage and lookup. This behavior also applies to database names and table aliases. 表名以小写存储在磁盘上,并且名称比较不区分大小写。MySQL在存储和查找时将所有表名转换为小写。此行为也适用于数据库名称和表别名。 Value = 3, Table and database names are stored on disk using the lettercase specified in the CREATE TABLE or CREATE DATABASE statement, but MySQL converts them to lowercase on lookup. Name comparisons are not case sensitive. This works only on file systems that are not case-sensitive! InnoDB table names and view names are stored in lowercase, as for Value = 1.表名和数据库名使用CREATE Table或CREATE database语句中指定的lettercase存储在磁盘上,但是MySQL在查找时将它们转换为小写。名称比较不区分大小写。这只适用于不区分大小写的文件系统!InnoDB表名和视图名以小写存储,Value = 1。 NOTE: lower_case_table_names can only be configured when initializing the server. Changing the lower_case_table_names setting after the server is initialized is prohibited. lower_case_table_names=1 Secure File Priv. 权限安全文件 secure-file-priv="C:/ProgramData/MySQL/MySQL Server 8.0/Uploads" The maximum amount of concurrent sessions the MySQL server will allow. One of these connections will be reserved for a user with SUPER privileges to allow the administrator to login even if the connection limit has been reached. MySQL服务器允许的最大并发会话量。这些连接中的一个将保留给具有超级特权的用户,以便允许管理员登录,即使已经达到连接限制。 max_connections=151 The number of open tables for all threads. Increasing this value increases the number of file descriptors that mysqld requires. Therefore you have to make sure to set the amount of open files allowed to at least 4096 in the variable "open-files-limit" in 为所有线程打开的表的数量。增加这个值会增加mysqld需要的文件描述符的数量。因此,您必须确保在[mysqld_safe]节中的变量“open-files-limit”中将允许打开的文件数量至少设置为4096 section [mysqld_safe] table_open_cache=2000 Maximum size for internal (in-memory) temporary tables. If a table grows larger than this value, it is automatically converted to disk based table This limitation is for a single table. There can be many of them. 内部(内存)临时表的最大大小。如果一个表比这个值大,那么它将自动转换为基于磁盘的表。可以有很多。 tmp_table_size=94M How many threads we should keep in a cache for reuse. When a client disconnects, the client's threads are put in the cache if there aren't more than thread_cache_size threads from before. This greatly reduces the amount of thread creations needed if you have a lot of new connections. (Normally this doesn't give a notable performance improvement if you have a good thread implementation.) 我们应该在缓存中保留多少线程以供重用。当客户机断开连接时,如果之前的线程数不超过thread_cache_size,则将客户机的线程放入缓存。如果您有很多新连接,这将大大减少所需的线程创建量(通常,如果您有一个良好的线程实现,这不会带来显著的性能改进)。 thread_cache_size=10 MyISAM Specific options The maximum size of the temporary file MySQL is allowed to use while recreating the index (during REPAIR, ALTER TABLE or LOAD DATA INFILE. If the file-size would be bigger than this, the index will be created through the key cache (which is slower). MySQL允许在重新创建索引时(在修复、修改表或加载数据时)使用临时文件的最大大小。如果文件大小大于这个值,那么索引将通过键缓存创建(这比较慢)。 myisam_max_sort_file_size=100G If the temporary file used for fast index creation would be bigger than using the key cache by the amount specified here, then prefer the key cache method. This is mainly used to force long character keys in large tables to use the slower key cache method to create the index. myisam_sort_buffer_size=179M Size of the Key Buffer, used to cache index blocks for MyISAM tables. Do not set it larger than 30% of your available memory, as some memory is also required by the OS to cache rows. Even if you're not using MyISAM tables, you should still set it to 8-64M as it will also be used for internal temporary disk tables. 如果用于快速创建索引的临时文件比这里指定的使用键缓存的文件大,则首选键缓存方法。这主要用于强制大型表中的长字符键使用较慢的键缓存方法来创建索引。 key_buffer_size=8M Size of the buffer used for doing full table scans of MyISAM tables. Allocated per thread, if a full scan is needed. 用于对MyISAM表执行全表扫描的缓冲区的大小。如果需要完整的扫描,则为每个线程分配。 read_buffer_size=256K read_rnd_buffer_size=512K INNODB Specific options INNODB特定选项 innodb_data_home_dir= Use this option if you have a MySQL server with InnoDB support enabled but you do not plan to use it. This will save memory and disk space and speed up some things. 如果您启用了一个支持InnoDB的MySQL服务器,但是您不打算使用它,那么可以使用这个选项。这将节省内存和磁盘空间,并加快一些事情。skip-innodb skip-innodb If set to 1, InnoDB will flush (fsync) the transaction logs to the disk at each commit, which offers full ACID behavior. If you are willing to compromise this safety, and you are running small transactions, you may set this to 0 or 2 to reduce disk I/O to the logs. Value 0 means that the log is only written to the log file and the log file flushed to disk approximately once per second. Value 2 means the log is written to the log file at each commit, but the log file is only flushed to disk approximately once per second. 如果设置为1,InnoDB将在每次提交时将事务日志刷新(fsync)到磁盘,这将提供完整的ACID行为。如果您愿意牺牲这种安全性,并且正在运行小型事务,您可以将其设置为0或2,以将磁盘I/O减少到日志。值0表示日志仅写入日志文件,日志文件大约每秒刷新一次磁盘。值2表示日志在每次提交时写入日志文件,但是日志文件大约每秒只刷新一次磁盘。 innodb_flush_log_at_trx_commit=1 The size of the buffer InnoDB uses for buffering log data. As soon as it is full, InnoDB will have to flush it to disk. As it is flushed once per second anyway, it does not make sense to have it very large (even with long transactions).InnoDB用于缓冲日志数据的缓冲区大小。一旦它满了,InnoDB就必须将它刷新到磁盘。由于它无论如何每秒刷新一次,所以将它设置为非常大的值是没有意义的(即使是长事务)。 innodb_log_buffer_size=5M InnoDB, unlike MyISAM, uses a buffer pool to cache both indexes and row data. The bigger you set this the less disk I/O is needed to access data in tables. On a dedicated database server you may set this parameter up to 80% of the machine physical memory size. Do not set it too large, though, because competition of the physical memory may cause paging in the operating system. Note that on 32bit systems you might be limited to 2-3.5G of user level memory per process, so do not set it too high. 与MyISAM不同,InnoDB使用缓冲池来缓存索引和行数据。设置的值越大,访问表中的数据所需的磁盘I/O就越少。在专用数据库服务器上,可以将该参数设置为机器物理内存大小的80%。但是,不要将它设置得太大,因为物理内存的竞争可能会导致操作系统中的分页。注意,在32位系统上,每个进程的用户级内存可能被限制在2-3.5G,所以不要设置得太高。 innodb_buffer_pool_size=20M Size of each log file in a log group. You should set the combined size of log files to about 25%-100% of your buffer pool size to avoid unneeded buffer pool flush activity on log file overwrite. However, note that a larger logfile size will increase the time needed for the recovery process. 日志组中每个日志文件的大小。您应该将日志文件的合并大小设置为缓冲池大小的25%-100%,以避免在覆盖日志文件时出现不必要的缓冲池刷新活动。但是,请注意,较大的日志文件大小将增加恢复过程所需的时间。 innodb_log_file_size=48M Number of threads allowed inside the InnoDB kernel. The optimal value depends highly on the application, hardware as well as the OS scheduler properties. A too high value may lead to thread thrashing. InnoDB内核中允许的线程数。最优值在很大程度上取决于应用程序、硬件以及OS调度程序属性。过高的值可能导致线程抖动。 innodb_thread_concurrency=9 The increment size (in MB) for extending the size of an auto-extend InnoDB system tablespace file when it becomes full. 增量大小(以MB为单位),用于在表空间满时扩展自动扩展的InnoDB系统表空间文件的大小。 innodb_autoextend_increment=128 The number of regions that the InnoDB buffer pool is divided into. For systems with buffer pools in the multi-gigabyte range, dividing the buffer pool into separate instances can improve concurrency, by reducing contention as different threads read and write to cached pages. InnoDB缓冲池划分的区域数。对于具有多gb缓冲池的系统,将缓冲池划分为单独的实例可以提高并发性,因为不同的线程对缓存页面的读写会减少争用。 innodb_buffer_pool_instances=8 Determines the number of threads that can enter InnoDB concurrently. 确定可以同时进入InnoDB的线程数 innodb_concurrency_tickets=5000 Specifies how long in milliseconds (ms) a block inserted into the old sublist must stay there after its first access before it can be moved to the new sublist. 指定插入到旧子列表中的块必须在第一次访问之后停留多长时间(毫秒),然后才能移动到新子列表。 innodb_old_blocks_time=1000 It specifies the maximum number of .ibd files that MySQL can keep open at one time. The minimum value is 10. 它指定MySQL一次可以打开的.ibd文件的最大数量。最小值是10。 innodb_open_files=300 When this variable is enabled, InnoDB updates statistics during metadata statements. 当启用此变量时,InnoDB会在元数据语句期间更新统计信息。 innodb_stats_on_metadata=0 When innodb_file_per_table is enabled (the default in 5.6.6 and higher), InnoDB stores the data and indexes for each newly created table in a separate .ibd file, rather than in the system tablespace. 当启用innodb_file_per_table(5.6.6或更高版本的默认值)时,InnoDB将每个新创建的表的数据和索引存储在单独的.ibd文件中,而不是系统表空间中。 innodb_file_per_table=1 Use the following list of values: 0 for crc32, 1 for strict_crc32, 2 for innodb, 3 for strict_innodb, 4 for none, 5 for strict_none. 使用以下值列表:0表示crc32, 1表示strict_crc32, 2表示innodb, 3表示strict_innodb, 4表示none, 5表示strict_none。 innodb_checksum_algorithm=0 The number of outstanding connection requests MySQL can have. This option is useful when the main MySQL thread gets many connection requests in a very short time. It then takes some time (although very little) for the main thread to check the connection and start a new thread. The back_log value indicates how many requests can be stacked during this short time before MySQL momentarily stops answering new requests. You need to increase this only if you expect a large number of connections in a short period of time. MySQL可以有多少未完成连接请求。当MySQL主线程在很短的时间内收到许多连接请求时,这个选项非常有用。然后,主线程需要一些时间(尽管很少)来检查连接并启动一个新线程。back_log值表示在MySQL暂时停止响应新请求之前的短时间内可以堆多少个请求。只有当您预期在短时间内会有大量连接时,才需要增加这个值。 back_log=80 If this is set to a nonzero value, all tables are closed every flush_time seconds to free up resources and synchronize unflushed data to disk. This option is best used only on systems with minimal resources. 如果将该值设置为非零值,则每隔flush_time秒关闭所有表,以释放资源并将未刷新的数据同步到磁盘。这个选项最好只在资源最少的系统上使用。 flush_time=0 The minimum size of the buffer that is used for plain index scans, range index scans, and joins that do not use 用于普通索引扫描、范围索引扫描和不使用索引执行全表扫描的连接的缓冲区的最小大小。 indexes and thus perform full table scans. join_buffer_size=200M The maximum size of one packet or any generated or intermediate string, or any parameter sent by the mysql_stmt_send_long_data() C API function. 由mysql_stmt_send_long_data() C API函数发送的一个包或任何生成的或中间字符串或任何参数的最大大小 max_allowed_packet=500M If more than this many successive connection requests from a host are interrupted without a successful connection, the server blocks that host from performing further connections. 如果在没有成功连接的情况下中断了来自主机的多个连续连接请求,则服务器将阻止主机执行进一步的连接。 max_connect_errors=100 Changes the number of file descriptors available to mysqld. You should try increasing the value of this option if mysqld gives you the error "Too many open files". 更改mysqld可用的文件描述符的数量。如果mysqld给您的错误是“打开的文件太多”,您应该尝试增加这个选项的值。 open_files_limit=4161 If you see many sort_merge_passes per second in SHOW GLOBAL STATUS output, you can consider increasing the sort_buffer_size value to speed up ORDER BY or GROUP BY operations that cannot be improved with query optimization or improved indexing. 如果在SHOW GLOBAL STATUS输出中每秒看到许多sort_merge_passes,可以考虑增加sort_buffer_size值,以加快ORDER BY或GROUP BY操作的速度,这些操作无法通过查询优化或改进索引来改进。 sort_buffer_size=1M The number of table definitions (from .frm files) that can be stored in the definition cache. If you use a large number of tables, you can create a large table definition cache to speed up opening of tables. The table definition cache takes less space and does not use file descriptors, unlike the normal table cache. The minimum and default values are both 400. 可以存储在定义缓存中的表定义的数量(来自.frm文件)。如果使用大量表,可以创建一个大型表定义缓存来加速表的打开。与普通的表缓存不同,表定义缓存占用更少的空间,并且不使用文件描述符。最小值和默认值都是400。 table_definition_cache=1400 Specify the maximum size of a row-based binary log event, in bytes. Rows are grouped into events smaller than this size if possible. The value should be a multiple of 256. 指定基于行的二进制日志事件的最大大小,单位为字节。如果可能,将行分组为小于此大小的事件。这个值应该是256的倍数。 binlog_row_event_max_size=8K If the value of this variable is greater than 0, a replication slave synchronizes its master.info file to disk. (using fdatasync()) after every sync_master_info events. 如果该变量的值大于0,则复制奴隶将其主.info文件同步到磁盘。(在每个sync_master_info事件之后使用fdatasync())。 sync_master_info=10000 If the value of this variable is greater than 0, the MySQL server synchronizes its relay log to disk. (using fdatasync()) after every sync_relay_log writes to the relay log. 如果这个变量的值大于0,MySQL服务器将其中继日志同步到磁盘。(在每个sync_relay_log写入到中继日志之后使用fdatasync())。 sync_relay_log=10000 If the value of this variable is greater than 0, a replication slave synchronizes its relay-log.info file to disk. (using fdatasync()) after every sync_relay_log_info transactions. 如果该变量的值大于0,则复制奴隶将其中继日志.info文件同步到磁盘。(在每个sync_relay_log_info事务之后使用fdatasync())。 sync_relay_log_info=10000 Load mysql plugins at start."plugin_x ; plugin_y". 开始时加载mysql插件。“plugin_x;plugin_y” plugin_load The TCP/IP Port the MySQL Server X Protocol will listen on. MySQL服务器X协议将监听TCP/IP端口。 loose_mysqlx_port=33060 本篇文章为转载内容。原文链接:https://blog.csdn.net/mywpython/article/details/89499852。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-08 09:56:02
129
转载
Hive
...以通过修改Hive的配置文件来增加Hive的连接数上限。比如,你可以尝试把hive.server2.thrift.max.worker.threads这个参数调大一些。 bash 在hive-site.xml文件中增加如下配置 hive.server2.thrift.max.worker.threads 100 2. 分批处理数据 如果你的数据集非常大,那么你可以尝试分批处理数据。这样可以避免一次性打开大量的连接。 sql -- 使用Hive的分区功能进行分批处理 CREATE TABLE my_table ( id INT, name STRING, age INT) PARTITIONED BY (year INT, month INT); INSERT INTO TABLE my_table PARTITION(year=2020, month=1) SELECT FROM small_table; 3. 管理连接 你应该确保你正确地管理你的连接,例如关闭不再使用的连接。 python 使用Python的psutil库来监控连接 import psutil process = psutil.Process() connections = process.connections(kind=(psutil.AF_INET, psutil.SOCK_STREAM)) for conn in connections: print(conn.laddr) 五、结论 Hive连接数超限是一个常见的问题,但也是一个可以通过适当的管理和优化来解决的问题。当你掌握了这个问题的来龙去脉,摸清了可能的解决方案后,咱们就能更溜地运用Hive这个工具,高效处理那些海量数据啦!
2023-02-16 22:49:34
455
素颜如水-t
ZooKeeper
...面来解决: 3.1 优化ZooKeeper配置 我们可以通过调整ZooKeeper的配置来改善服务器的性能。例如,我们可以增加服务器的内存大小,提高最大队列长度,减少watcher的数量等。 以下是一些常用的ZooKeeper配置参数: xml zookeeper.maxClientCnxns 6000 zookeeper.server.maxClientCnxns 6000 zookeeper.jmx.log4j.disableAppender true zookeeper.clientPort 2181 zookeeper.dataDir /var/lib/zookeeper zookeeper.log.dir /var/log/zookeeper zookeeper.maxSessionTimeout 40000 zookeeper.minSessionTimeout 5000 zookeeper.initLimit 10 zookeeper.syncLimit 5 zookeeper.tickTime 2000 zookeeper.serverTickTime 2000 3.2 增加ZooKeeper服务器数量 通过增加ZooKeeper服务器的数量,可以有效地分散负载,降低单个服务器的压力。不过要注意,要是集群里的节点数量一多起来,管理跟维护这些家伙可就有点让人头疼了。 3.3 数据分片 对于数据量过大的情况,我们可以通过数据分片的方式来解决。ZooKeeper这小家伙有个很实用的功能,就是它能创建namespace,就好比给你的数据分门别类,弄出多个“小仓库”。这样一来,你就可以按照自己的需求,把这些“小仓库”分布到不同的服务器上,让它们各司其职,协同工作。 java Set namespaces = curatorFramework.listChildren().forPath("/"); for (String namespace : namespaces) { System.out.println("Namespace: " + namespace); } 四、结论 总的来说,解决ZooKeeper服务器资源不足的问题,需要从优化配置、增加服务器数量和数据分片等多个角度进行考虑。同时呢,咱们也得把ZooKeeper这家伙的工作原理摸得门儿清,这样在遇到各种幺蛾子问题时,才能更顺溜地搞定它们。
2023-01-31 12:13:03
230
追梦人-t
Flink
.... 调整Flink的配置 有些配置参数可能会影响RocksDBStateBackend的行为。例如,你可以增加RocksDB的垃圾回收频率,或者调整它的日志级别,以便更好地了解可能的问题。 五、总结 总的来说,“RocksDBStateBackend corruption”是一个常见的问题,但也是可以解决的。只要我们把配置调对,策略定准,就能最大程度地避免数据丢失这个大麻烦,确保无论何时何地,咱们的作业都能快速恢复如初,一切尽在掌握之中。当然啦,最顶呱呱的招儿还是防患于未然。所以呐,你就得养成定期给你的数据做个“备胎”的好习惯,同时也要像关心身体健康那样,随时留意你系统的运行状态。 六、代码示例 以下是使用Flink的code实现state的示例: java StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setStateBackend(new RocksDBStateBackend("path/to/your/state")); DataStream text = env.socketTextStream("localhost", 9999); text.map(new MapFunction() { @Override public Integer map(String value) throws Exception { return Integer.parseInt(value); } }).keyBy(0) .reduce(new ReduceFunction() { @Override public Integer reduce(Integer value1, Integer value2) throws Exception { return value1 + value2; } }).print(); 在这个例子中,我们将所有的中间结果(即状态)保存到了指定的目录下。如果作业不幸搞砸了,我们完全可以拽回这个目录下的文件,让一切恢复到之前的状态。 以上就是我关于“RocksDBStateBackend corruption: State backend detected corruption during recovery”的理解和分析,希望能对你有所帮助。
2023-09-05 16:25:22
417
冬日暖阳-t
Tesseract
...通过实例代码展示如何优化Tesseract在面对多语言混合文本时的表现。 2. 多语言混合文本识别的难题 --- 想象一下这样一种场景:一份文档中混杂着英文、中文和日文等不同语言的文字。对于Tesseract这货来说,识别单独一种语言时,表现那可是相当赞的。不过呢,一旦遇到这种“乱炖”式的多种语言混合场景,它可能就有点犯迷糊了。其实呢,Tesseract这家伙在训练的时候,专门是学了一门针对特定语言的“独门秘籍”。不过呢,一旦遇到一张图片里混杂了好几种语言的情况,它可能就有点犯晕了,因为各种语言的特点相互交错,让它傻傻分不清楚。 3. Tesseract处理多语言混合文本的实战演示 --- python import pytesseract from PIL import Image 假设我们有一个包含英文、中文和日文的混合文本图片文件 'mixed_languages.png' img = Image.open('mixed_languages.png') 默认情况下,Tesseract会尝试使用其已训练的语言模型进行识别 default_result = pytesseract.image_to_string(img) 输出结果可能会出现混淆,因为Tesseract默认只识别一种语言 为了改进识别效果,我们可以明确指定要识别的所有语言 multi_lang_result = pytesseract.image_to_string(img, lang='eng+chi_sim+jpn') 这样,Tesseract将会尝试结合三种语言模型来解析图片中的文本,理论上可以提高混合文本的识别准确率 4. 解决策略与思考过程 --- 尽管上述方法可以在一定程度上缓解多语言混合文本的识别问题,但并不总是万无一失。Tesseract在识别混合文本时仍面临如下挑战: - 语言边界检测:Tesseract在没有明确语境的情况下难以判断哪部分文字属于哪种语言。 - 语言权重分配:即使指定了多种语言,Tesseract也可能无法准确地为不同区域分配合适的语言权重。 为此,我们可以尝试以下策略: - 预处理:利用图像分割技术,根据字体、颜色、位置等因素对不同语言区域进行划分,然后分别用对应的语言模型进行识别。 - 调整配置:Tesseract支持一些高级配置选项,如--oem和--psm,通过合理设置这些参数,有可能改善识别性能。 - 自定义训练:如果条件允许,还可以针对特定的混合文本类型,收集数据并训练自定义的混合语言模型。 5. 结论与探讨 --- 虽然Tesseract在处理多语言混合文本时存在挑战,但我们不能否认其在解决复杂OCR问题上的巨大潜力。当你真正摸透了它的运行门道,再灵活耍弄各种小策略,咱们就能一步步地把它在混合文本识别上的表现调校得更上一层楼。当然,这个过程不仅需要耐心调试,更需人类的智慧与创造力。每一次对技术边界的探索都是对人类理解和掌握世界的一次深化,让我们一起期待未来的Tesseract能够更好地服务于我们的多元文化环境吧! 以上所述仅为基本思路,实际应用中还需结合具体场景进行细致分析与实验验证。说真的,机器学习这片领域就像一个充满无尽奇妙的迷宫乐园,我们得揣着满满的好奇心和满腔热情,去尝试每一条可能的道路,才能真正找到那个专属于自己的、最完美的解决方案。
2023-03-07 23:14:16
136
人生如戏
RocketMQ
...比较大,那么你可以在配置文件中增加最大连接数的值。例如,你可以将最大连接数修改为2000,如下所示: consumer.maxConsumeThreadNumber=2000 但是需要注意的是,这种方法并不是长久之计。因为随着连接数的增加,系统的负载也会增加,可能会导致系统性能下降。 2. 使用消息分发策略 另一种解决方案是使用消息分发策略。你可以根据你的业务实际情况,灵活地把消息分配给多个不同的消费者,就像分蛋糕一样均匀切分,而不是让所有的消费者像抢红包那样争抢同一条消息。这样能够大大缓解每位用户连接时的压力,确保大家不会遇到“连接人数爆棚”的尴尬状况。 以下是一个简单的消息分发策略的例子: java public class MyMessageListener implements MessageListenerConcurrently { @Override public void consumeMessage(List msgs, ConsumeContext context) { for (MessageExt msg : msgs) { String tag = msg.getProperty(MessageConst.PROPERTY_KEY_TAG); if ("tag1".equals(tag)) { // 消费者A处理"tag1"的消息 } else if ("tag2".equals(tag)) { // 消费者B处理"tag2"的消息 } } } } 在这个例子中,我们根据消息的标签来决定由哪个消费者来处理这条消息。这样,即使有很多消费者在竞争同一个消息,也不会因为连接数过多而导致问题。 四、总结 总的来说,“消费者的连接数超过限制”这个问题并不是无法解决的。要解决这个问题,咱们可以试试两个招儿:一是提高最大连接数,二是采用消息分发策略。这样一来,就能妥妥地避免这个问题冒头了。不过呢,咱也要明白这么个道理,虽然这些招数能帮咱们临时把问题糊弄过去,可它们压根儿解决不了问题的本质啊。所以,在我们捣鼓系统设计的时候,最好尽可能把连接数量压到最低,这样一来,才能更好地确保系统的稳定性和随时能用性。
2023-10-04 08:19:39
132
心灵驿站-t
SeaTunnel
...用SeaTunnel配置的实例代码,实实在在地教你搞定这些问题的小妙招。 2. SFTP连接与认证原理浅析 首先,让我们理解一下SFTP的基本工作原理。SFTP(Secure File Transfer Protocol)是一种安全文件传输协议,它基于SSH协议,确保了数据在传输过程中的安全性。在咱们建立连接并开始认证这一步的时候,客户端必须拿出一些硬货,比如有效的用户名、密码这些身份通行证,还有SSH密钥这类高级验证工具,才能顺利过关,完成身份核实的过程。如果碰到网络连接老是掉线,或者认证失败这种情况,那可能是因为网络环境时好时坏、服务器设置有点问题,或者是密钥对不上号等多种原因造成的。 3. SeaTunnel对接SFTP常见问题及对策 (3.1) 连接不稳定问题 - 场景描述: 在使用SeaTunnel从SFTP读取或写入数据时,可能会遇到连接频繁断开、重连的情况。 - 原因分析: 可能是由于网络延迟、丢包、SFTP服务器超时设置过短等因素引起。 - 解决方案与代码示例: yaml 在SeaTunnel的source或sink配置中添加相关参数 sftp: host: 'your_sftp_host' port: 22 username: 'your_username' password: 'your_password' connectionTimeout: 60000 设置连接超时时间(单位毫秒) soTimeout: 60000 设置读写超时时间(单位毫秒) 这里我们通过调整connectionTimeout和soTimeout参数,为SFTP连接预留更充足的响应时间,有助于改善连接稳定性。 (3.2) 认证失败问题 - 场景描述: 提供正确的用户名、密码或密钥后,仍无法成功连接SFTP服务器。 - 原因分析: 密码错误、密钥对不匹配、权限不足等情况都可能导致认证失败。 - 解决方案与代码示例: yaml sftp: host: 'your_sftp_host' port: 22 privateKeyPath: '/path/to/your/private_key' 如果使用密钥认证,指定私钥文件路径 passphrase: 'your_passphrase' 若私钥有密码,请填写此字段 确保提供的认证信息准确无误,对于密钥认证,不仅要提供正确的私钥路径,还需确认是否需要提供对应的passphrase(如果有的话)。此外,检查SFTP服务器上对应用户的权限设置也是必要的步骤。 4. 深度探讨与实践优化 面对SFTP连接和认证问题,除了上述基础配置外,我们还需要关注: - 网络状况监控与优化: 保持良好的网络环境,减少网络抖动带来的影响。 - 日志分析与调试: 配置详细的日志输出级别,通过查看SeaTunnel运行日志来定位问题的具体原因。 - 定期健康检查: 定期检查并更新SFTP服务器的配置,包括但不限于用户权限、防火墙规则、服务器资源占用情况等。 5. 结语 在大数据时代,数据的稳定高效传输至关重要。通过合理配置SeaTunnel,我们可以更好地应对SFTP连接不稳定或认证失败的问题。在这个过程中,咱们得接地气儿,灵活运用各种招数,针对实际情况见招拆招。就像是调音师调试乐器那样,我们也得不断优化调整,最终目的是为了让数据管道顺顺当当地跑起来,一点儿不卡壳。记住了啊,每一个技术难题其实都是个学习和进步的好机会,只要我们坚持不断去摸索、去探究,总有一天会找到那个最完美的解决方案,让问题迎刃而解。
2023-12-13 18:13:39
269
秋水共长天一色
ClickHouse
如何配置ClickHouse的数据中心以满足特定需求? 在大数据时代,ClickHouse作为一款高性能的列式数据库管理系统,以其出色的查询速度和处理能力赢得了众多企业的青睐。然而,为了让ClickHouse数据中心彻底展现它的威力,并且完美适应特定业务环境的需求,我们得给它来个“量体裁衣”式的精细设置。嘿,伙计们,这篇内容将会手把手地带你们踏上一段实战之旅,咱们一步步地通过具体的步骤和鲜活的代码实例,来揭开如何搭建一个既高效又稳定的ClickHouse数据中心的秘密面纱。 1. 确定硬件配置与集群架构 首先,我们从硬件配置和集群设计开始。根据业务的具体需求,数据量大小和并发查询的压力等因素,就像指挥棒一样,会直接影响到我们选择硬件资源的规格以及集群结构的设计布局。比如说,如果我们的业务需要处理海量数据或者面临大量的并发查询挑战,那就得像搭积木一样,精心设计和构建强大的硬件支撑体系以及合理的集群架构,才能确保整个系统的稳定高效运行。 例如,如果您的业务涉及到PB级别的海量数据存储和实时分析,可能需要考虑采用分布式集群部署的方式,每个节点配置较高的CPU核心数、大内存以及高速SSD硬盘: yaml 配置文件(/etc/clickhouse-server/config.xml) true node1.example.com 9000 这里展示了如何配置一个多副本、多分片的ClickHouse集群。my_cluster是集群名称,内部包含多个shard,每个shard又包含多个replica,确保了高可用性和容错性。 2. 数据分区策略与表引擎选择 ClickHouse支持多种表引擎,如MergeTree系列,这对于数据分区和优化查询性能至关重要。以MergeTree为例,我们可以根据时间戳或其他业务关键字段进行分区: sql CREATE TABLE my_table ( id Int64, timestamp DateTime, data String ) ENGINE = MergeTree() PARTITION BY toYYYYMMDD(timestamp) ORDER BY (timestamp, id); 上述SQL语句创建了一个名为my_table的表,使用MergeTree引擎,并按照timestamp字段进行分区,按timestamp和id排序,这有助于提高针对时间范围的查询效率。 3. 调优配置参数 ClickHouse提供了一系列丰富的配置参数以适应不同的工作负载。比如,对于写入密集型场景,可以调整以下参数: yaml 1048576 增大插入块大小 16 调整后台线程池大小 16 最大并行查询线程数 这些参数可以根据实际服务器性能和业务需求进行适当调整,以达到最优写入性能。 4. 监控与运维管理 为了保证ClickHouse数据中心的稳定运行,必须配备完善的监控系统。ClickHouse自带Prometheus metrics exporter,方便集成各类监控工具: bash 启动Prometheus exporter clickhouse-server --metric_log_enabled=1 同时,合理规划备份与恢复策略,利用ClickHouse的备份工具或第三方工具实现定期备份,确保数据安全。 总结起来,配置ClickHouse数据中心是一个既需要深入理解技术原理,又需紧密结合业务实践的过程。当面对特定的需求时,我们得像玩转乐高积木一样,灵活运用ClickHouse的各种强大功能。从挑选合适的硬件设备开始,一步步搭建起集群架构,再到精心设计数据模型,以及日常的运维调优,每一个环节都不能落下,都要全面、细致地去琢磨和优化,确保整个系统运作流畅,高效满足需求。在这个过程中,我们得不断摸爬滚打、动动脑筋、灵活变通,才能让我们的ClickHouse数据中心持续进步,更上一层楼地为业务发展添砖加瓦、保驾护航。
2023-07-29 22:23:54
509
翡翠梦境
Hive
... 三、案例分析 优化Hive查询性能的策略 为了更好地利用Hive的并行计算能力,我们可以采取以下几种策略来优化查询性能: 1. 合理使用分区和表结构 sql CREATE TABLE sales ( date STRING, product STRING, quantity INT ) PARTITIONED BY (year INT, month INT); 分区操作能帮助Hive在执行查询时快速定位到特定的数据集,从而减少扫描的文件数量,提高查询效率。 2. 利用索引增强查询性能 sql CREATE INDEX idx_sales_date ON sales (date); 索引可以显著加快基于某些列的查询速度,特别是在进行过滤和排序操作时。 3. 优化查询语句 - 避免使用昂贵的函数和复杂的子查询。 - 使用EXPLAIN命令预览查询计划,识别瓶颈并进行调整。 sql EXPLAIN SELECT FROM sales WHERE year = 2023 AND month = 5; 4. 批处理与实时查询分离 对于频繁执行的查询,考虑将其转换为更高效的批处理作业,而非实时查询。 四、实践与经验分享 在实际操作中,我们发现以下几点经验尤为重要: - 数据预处理:确保数据在导入Hive前已经进行了清洗和格式化,减少无效数据的处理时间。 - 定期维护:定期清理不再使用的数据和表,以及更新索引,保持系统的高效运行。 - 监控与调优:利用Hive Metastore提供的监控工具,持续关注查询性能,并根据实际情况调整配置参数。 五、结论 并行计算与Hive的未来展望 随着大数据技术的不断发展,Hive在并行计算领域的潜力将进一步释放。哎呀,兄弟!咱们得好好调整数据存档的布局,还有那些查询命令和系统的设定,这样才能让咱们的数据处理快如闪电,用户体验棒棒哒!到时候,用咱们的服务就跟喝着冰镇可乐一样爽,那叫一个舒坦啊!哎呀,你知道不?就像咱们平时用的工具箱里又添了把更厉害的瑞士军刀,那就是Apache Drill这样的新技术。这玩意儿一出现,Hive这个大数据分析的家伙就更牛了,能干的事情更多,效率也更高,就像开挂了一样。它现在不仅能快如闪电地处理数据,还能像变魔术一样,根据我们的需求变出各种各样的分析结果。这下子,咱们做数据分析的时候,可就轻松多了! --- 本文旨在探讨Hive如何通过并行计算能力提升数据处理效率,通过具体实例展示了如何优化Hive查询性能,并分享了实践经验。希望这些内容能对您在大数据分析领域的工作提供一定的启发和帮助。
2024-09-13 15:49:02
35
秋水共长天一色
Flink
...de public String map(String value) throws Exception { return value.toUpperCase(); } }); transformed.print(); env.execute("Simple Flink Job"); 这段代码展示了如何创建一个简单的Flink任务,该任务从一个Socket接收字符串数据,将其转换为大写,并打印结果。这里的source和transformed就是构成JobGraph的一部分。 2. ExecutionPlan 通往高效执行的道路 接下来,我们来看看ExecutionPlan。当你的JobGraph准备好之后,Flink会根据它生成一个ExecutionPlan。这个计划详细说明了怎么在集群上同时跑数据流,包括怎么安排任务、分配资源之类的。 为什么ExecutionPlan至关重要? - 性能优化:ExecutionPlan考虑到了各种因素(如网络延迟、机器负载等)来优化任务的执行效率,确保数据流能够快速准确地流动。 - 容错机制:通过合理的任务划分和错误恢复策略,ExecutionPlan可以保证即使在某些节点失败的情况下,整个系统也能稳定运行。 示例代码: 虽然ExecutionPlan本身并不直接提供给用户进行编程操作,但你可以通过配置参数来影响它的生成。例如: java env.setParallelism(4); // 设置并行度为4 这条语句会影响ExecutionPlan中任务的并行执行方式。更高的并行度通常能让吞吐量变得更好,但同时也可能会让网络通信变得更复杂,增加不少额外的工作量。 3. 探索背后的秘密 JobGraph与ExecutionPlan的互动 现在,让我们思考一下JobGraph和ExecutionPlan之间的关系。可以说,JobGraph是ExecutionPlan的基础,没有一个清晰的JobGraph,就无法生成有效的ExecutionPlan。ExecutionPlan就是JobGraph的具体操作指南,它告诉你怎么把这些抽象的想法变成实实在在的计算任务。 思考与探讨: - 在设计你的Flink应用程序时,是否考虑过JobGraph的结构对最终性能的影响? - 你有没有尝试过调整ExecutionPlan的某些参数来提升应用程序的效率? 4. 实践中的挑战与解决方案 最后,我想分享一些我在使用Flink过程中遇到的实际问题及解决方案。 问题1:数据倾斜导致性能瓶颈 - 原因分析:数据分布不均匀可能导致某些算子处理的数据量远大于其他算子,从而形成性能瓶颈。 - 解决办法:可以通过重新设计JobGraph,比如引入更多的分区策略或调整算子的并行度来缓解这个问题。 问题2:内存溢出 - 原因分析:长时间运行的任务可能会消耗大量内存,尤其是在处理大数据集时。 - 解决办法:合理设置Flink的内存管理策略,比如增加JVM堆内存或利用Flink的内存管理API来控制内存使用。 --- 好了,朋友们,这就是我对Flink中的JobGraph和ExecutionPlan的理解和分享。希望这篇文章能让你深深体会到它们的价值,然后在你的项目里大展身手,随意挥洒!如果你有任何疑问或者想要进一步讨论的话题,欢迎随时留言交流! 记住,学习技术就像一场旅行,重要的是享受过程,不断探索未知的领域。希望我们在数据流的世界里都能成为勇敢的探险家!
2024-11-05 16:08:03
111
雪落无痕
Dubbo
... Dubbo的性能优化实践分享 一、引言 在构建分布式系统时,Dubbo作为一款轻量级、高性能的RPC(Remote Procedure Call)框架,因其简洁的API、丰富的插件机制以及强大的性能表现而备受青睐。本文将围绕Dubbo的性能优化展开讨论,分享实际应用中的经验和技巧,旨在帮助开发者在构建分布式服务时,能够更高效地利用Dubbo,提升系统整体性能。 二、Dubbo基础概览 Dubbo的核心功能包括远程调用、服务注册与发现、负载均衡等,它支持多种通信协议,并且提供了一套完整的开发框架。哎呀,用Dubbo开发啊?那可得好好琢磨琢磨!首先,得想想怎么合理地给服务器和客户端搭桥铺路,就像给好朋友之间搭建方便沟通的桥梁一样。别让信息传得慢吞吞的,还得考虑怎么优化服务,就像给跑车换上更轻便、更给力的引擎,让性能飙起来!毕竟,谁都不想自己的程序像蜗牛一样爬行吧?所以,得花点心思在这上面,让用户体验嗖的一下就上去了! 三、性能优化策略 1. 网络层优化 - 减少网络延迟:通过减少数据包大小、优化编码方式、使用缓存机制等方式降低网络传输的开销。 - 选择合适的网络协议:根据实际应用场景选择HTTP、TCP或其他协议,HTTP可能在某些场景下提供更好的性能和稳定性。 2. 缓存机制 - 服务缓存:利用Dubbo的本地缓存或第三方缓存如Redis,减少对远程服务的访问频率,提高响应速度。 - 结果缓存:对于经常重复计算的结果,可以考虑将其缓存起来,避免重复计算带来的性能损耗。 3. 负载均衡策略 - 动态调整:根据服务的负载情况,动态调整路由规则,优先将请求分发给负载较低的服务实例。 - 健康检查:定期检查服务实例的健康状态,剔除不可用的服务,确保请求始终被转发到健康的服务上。 4. 参数优化 - 调优配置:合理设置Dubbo的相关参数,如超时时间、重试次数、序列化方式等,以适应不同的业务需求。 - 并发控制:通过合理的线程池配置和异步调用机制,有效管理并发请求,避免资源瓶颈。 四、实战案例 案例一:服务缓存实现 java // 配置本地缓存 @Reference private MyService myService; public void doSomething() { // 获取缓存,若无则从远程调用获取并缓存 String result = cache.get("myKey", () -> myService.doSomething()); System.out.println("Cache hit/miss: " + (result != null ? "hit" : "miss")); } 案例二:动态负载均衡 java // 创建负载均衡器实例 LoadBalance loadBalance = new RoundRobinLoadBalance(); // 配置服务列表 List serviceUrls = Arrays.asList("service1://localhost:8080", "service2://localhost:8081"); // 动态选择服务实例 String targetUrl = loadBalance.choose(serviceUrls); MyService myService = new RpcReference(targetUrl); 五、总结与展望 通过上述的实践分享,我们可以看到,Dubbo的性能优化并非一蹴而就,而是需要在实际项目中不断探索和调整。哎呀,兄弟,这事儿啊,关键就是得会玩转Dubbo的各种酷炫功能,然后结合你手头的业务场景,好好打磨打磨那些参数,让它发挥出最佳状态。就像是调酒师调鸡尾酒,得看人下菜,看场景定参数,这样才能让产品既符合大众口味,又能彰显个性特色。哎呀,你猜怎么着?Dubbo这个大宝贝儿,它一直在努力学习新技能,提升自己呢!就像咱们人一样,技术更新换代快,它得跟上节奏,对吧?所以,未来的它呀,肯定能给咱们带来更多简单好用,性能超棒的功能!这不就是咱们开发小能手的梦想嘛——搭建一个既稳当又高效的分布式系统?想想都让人激动呢! 结语 在分布式系统构建的过程中,性能优化是一个持续的过程,需要开发者具备深入的理解和技术敏感度。嘿!小伙伴们,如果你是Dubbo的忠实用户或者是打算加入Dubbo大家庭的新手,这篇文章可是为你量身打造的!我们在这里分享了一些实用的技巧和深刻的理解,希望能激发你的灵感,让你在使用Dubbo的过程中更得心应手,共同创造分布式系统那片美丽的天空。快来一起探索,一起成长吧!
2024-07-25 00:34:28
410
百转千回
RocketMQ
...失风险的策略 1. 配置优化 合理设置RocketMQ的配置参数,如消息重试次数、消费超时时间等,确保在异常情况下,消息可以被正确处理或重试。 java // 示例代码:设置消息重试次数 Properties props = new Properties(); props.setProperty("producer.transactionCheckEnabled", "false"); props.setProperty("producer.transactionTimeout", "60000"); props.setProperty("producer.maxReconsumeTimes", "5"); // 设置最大重试次数为5次 RMQSender sender = new RMQSender("localhost:18831", "myQueue", props); 2. 监控与报警 建立一套完善的监控系统,实时监测RocketMQ的运行状态,一旦出现异常,立即触发报警机制。 bash 假设使用Prometheus进行监控 prometheus: - job_name: 'rocketmq' metrics_path: '/actuator/metrics' static_configs: - targets: ['localhost:8080'] labels: application: 'rocketmq' 3. 备份与恢复策略 定期对RocketMQ的元数据和消息进行备份,以便在发生灾难性事件时快速恢复服务。 bash 使用HDFS作为存储时,可以利用HDFS的备份功能 hdfs dfs -copyToLocal /path/to/backup /local/path/ 4. 容错与高可用架构设计 在应用层面考虑容错机制,如使用负载均衡、故障转移等策略,确保在单点故障时,系统仍能正常运行。 java // 使用Nacos进行服务发现和配置中心管理 @Value("${service.provider}") private String serviceProvider; @Bean public ProviderConfig providerConfig() { return new ProviderConfig(serviceProvider); } 四、结论 通过上述策略的实施,我们可以显著降低使用RocketMQ时数据丢失的风险。关键在于合理配置、有效监控、备份恢复以及高可用架构的设计。在实际应用中,还需要根据业务的具体需求和场景,灵活调整策略,以达到最佳的数据持久化效果。哎呀,兄弟!技术这东西,得不停琢磨,多实践,别老是原地踏步。咱们得时不时调整一下系统这架机器的零件,让它跑得既快又稳当。这样,咱们的应用服务才不会卡壳,用户们用起来也舒心。这可是保证业务顺畅运行的关键!
2024-10-02 15:46:59
573
蝶舞花间
ElasticSearch
...标记为不可用。 - 配置错误:比如分配给节点的资源不够,导致其无法启动。 对于我来说,问题出在第二个点上——磁盘空间不足。我当时为了省钱,给服务器分配的空间少得可怜,结果没多久就发现磁盘直接爆满,把自己都吓了一跳!于是ElasticSearch很生气,直接把该节点踢出了集群。 --- 3. 解决方案一 扩容磁盘空间 既然问题找到了,那就动手解决吧!首先,我决定先扩展磁盘容量。这一步其实很简单,只要登录服务器,增加磁盘大小就行。具体步骤如下: bash 查看当前磁盘状态 df -h 扩展磁盘(假设你已经购买了额外的存储) sudo growpart /dev/xvda 1 sudo resize2fs /dev/xvda1 完成后记得重启ElasticSearch服务: bash sudo systemctl restart elasticsearch 重启之后,神奇的事情发生了——我的节点重新上线了!不过这里有个小技巧分享给大家:如果你不确定扩容是否成功,可以通过以下命令检查磁盘使用情况: bash df -h 看到磁盘空间变大了,心里顿时舒坦了不少。 --- 4. 解决方案二 调整ElasticSearch配置 当然啦,仅仅扩容还不够,还需要优化ElasticSearch的配置文件。特别是那些容易导致内存不足或磁盘占用过高的参数,比如indices.memory.index_buffer_size和indices.store.throttle.max_bytes_per_sec。修改后的配置文件大概长这样: yaml cluster.routing.allocation.disk.threshold_enabled: true cluster.routing.allocation.disk.watermark.low: 85% cluster.routing.allocation.disk.watermark.high: 90% cluster.routing.allocation.disk.watermark.flood_stage: 95% cluster.info.update.interval: 30s 这些设置的意思是告诉ElasticSearch,当磁盘使用率达到85%时开始警告,达到90%时限制写入,超过95%时完全停止操作。这样可以有效避免再次出现类似的问题。 --- 5. 实战演练 代码中的应对策略 除了调整配置,我们还可以通过编写脚本来监控和处理NodeNotActiveException。比如,下面这段Java代码展示了如何捕获异常并记录日志: java import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; public class ElasticSearchExample { public static void main(String[] args) { RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http"))); try { CreateIndexRequest request = new CreateIndexRequest("test_index"); CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT); System.out.println("Index created: " + response.isAcknowledged()); } catch (Exception e) { if (e instanceof ClusterBlockException) { System.err.println("Cluster block detected: " + e.getMessage()); } else { System.err.println("Unexpected error: " + e.getMessage()); } } finally { try { client.close(); } catch (IOException ex) { System.err.println("Failed to close client: " + ex.getMessage()); } } } } 这段代码的作用是在创建索引时捕获可能发生的异常,并根据异常类型采取不同的处理方式。如果遇到ClusterBlockException,我们可以选择延迟重试或者其他补偿措施。 --- 6. 总结与反思 成长路上的一课 通过这次经历,我深刻体会到,作为一名开发者,不仅要掌握技术细节,还要学会从实际问题出发,找到最优解。NodeNotActiveException这个错误看着不起眼,但其实背后有不少门道呢!比如说,你的服务器硬件是不是有点吃不消了?集群那边有没有啥小毛病没及时发现?还有啊,咱们平时运维的时候是不是也有点松懈了?这些都是得好好琢磨的地方! 最后,我想说的是,技术学习的过程就像爬山一样,有时候会遇到陡峭的山坡,但只要坚持下去,总能看到美丽的风景。希望这篇文章能给大家带来一些启发和帮助!如果还有其他疑问,欢迎随时交流哦~
2025-03-14 15:40:13
64
林中小径
MySQL
...t/15/ 步骤二:配置Hadoop和MySQL 在开始之前,请确保您的Hadoop和MySQL已经正确配置并运行。 对于Hadoop,您可以查看以下教程:https://hadoop.apache.org/docs/r2.7.3/hadoop-project-dist/hadoop-common/SingleCluster.html 对于MySQL,您可以参考官方文档:https://dev.mysql.com/doc/refman/8.0/en/installing-binary-packages.html 步骤三:创建MySQL表 在开始导出数据之前,我们需要在MySQL中创建一个表来存储数据。以下是一个简单的例子: CREATE TABLE students ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(45) DEFAULT NULL, age int(11) DEFAULT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 这个表将包含学生的ID、姓名和年龄字段。 步骤四:编写Sqoop脚本 现在我们可以使用Sqoop将HDFS中的数据导入到MySQL表中。以下是一个基本的Sqoop脚本示例: bash -sqoop --connect jdbc:mysql://localhost:3306/test \ -m 1 \ --num-mappers 1 \ --target-dir /user/hadoop/students \ --delete-target-dir \ --split-by id \ --as-textfile \ --fields-terminated-by '|' \ --null-string 'NULL' \ --null-non-string '\\N' \ --check-column id \ --check-nulls \ --query "SELECT id, name, age FROM students WHERE age > 18" 这个脚本做了以下几件事: - 使用--connect选项连接到MySQL服务器和测试数据库。 - 使用-m和--num-mappers选项设置映射器的数量。在这个例子中,我们只有一个映射器。 - 使用--target-dir选项指定输出目录。在这个例子中,我们将数据导出到/user/hadoop/students目录下。 - 使用--delete-target-dir选项删除目标目录中的所有内容,以防数据冲突。 - 使用--split-by选项指定根据哪个字段进行拆分。在这个例子中,我们将数据按学生ID进行拆分。 - 使用--as-textfile选项指定数据格式为文本文件。 - 使用--fields-terminated-by选项指定字段分隔符。在这个例子中,我们将字段分隔符设置为竖线(|)。 - 使用--null-string和--null-non-string选项指定空值的表示方式。在这个例子中,我们将NULL字符串设置为空格,将非字符串空值设置为\\N。 - 使用--check-column和--check-nulls选项指定检查哪个字段和是否有空值。在这个例子中,我们将检查学生ID是否为空,并且如果有,将记录为NULL。 - 使用--query选项指定要从中读取数据的SQL查询语句。在这个例子中,我们只选择年龄大于18的学生。 请注意,这只是一个基本的示例。实际的脚本可能会有所不同,具体取决于您的数据和需求。 步骤五:运行Sqoop脚本 最后,我们可以使用以下命令运行Sqoop脚本: bash -sqoop \ -Dmapreduce.job.user.classpath.first=true \ --libjars $SQOOP_HOME/lib/mysql-connector-java-8.0.24.jar \ --connect jdbc:mysql://localhost:3306/test \ -m 1 \ --num-mappers 1 \ --target-dir /user/hadoop/students \ --delete-target-dir \ --split-by id \ --as-textfile \ --fields-terminated-by '|' \ --null-string 'NULL' \ --null-non-string '\\N' \ --check-column id \ --check-nulls \ --query "SELECT id, name, age FROM students WHERE age > 18" 注意,我们添加了一个-Dmapreduce.job.user.classpath.first=true参数,这样就可以保证我们的自定义JAR包在任务的classpath列表中处于最前面的位置。 如果一切正常,我们应该可以看到一条成功的消息,并且可以在MySQL中看到导出的数据。 总结 本文介绍了如何使用Apache Sqoop将HDFS中的数据导出到MySQL数据库。咱们先给环境捯饬得妥妥当当,然后捣鼓出一个MySQL表,再接再厉,编了个Sqoop脚本。最后,咱就让这个脚本大展身手,把数据导出溜溜的。希望这篇文章能帮助你解决这个问题!
2023-04-12 16:50:07
247
素颜如水_t
Hadoop
...力!由于它具有高度可配置性和灵活性,因此可以用于各种数据处理场景。 二、Hadoop与Apache NiFi集成 为了使Hadoop与Apache NiFi进行集成,我们需要安装Apache NiFi并将其添加到Hadoop集群中。具体步骤如下: 1. 安装Apache NiFi 我们可以从Apache NiFi的官方网站下载最新的稳定版本,并按照官方提供的指导手册进行安装。在安装这个东西的时候,我们得先调整几个基础配置,就好比NiFi的端口号码啦,还有它怎么进行身份验证这些小细节。 2. 将Apache NiFi添加到Hadoop集群中 为了让Apache NiFi能够访问Hadoop集群中的数据,我们需要配置NiFi的环境变量。首先,我们需要确定Hadoop集群的位置,然后在NiFi的环境中添加以下参数: javascript export HADOOP_CONF_DIR=/path/to/hadoop/conf export HADOOP_HOME=/path/to/hadoop 3. 配置NiFi数据源 接下来,我们需要配置NiFi的数据源,使其能够连接到Hadoop集群中的HDFS文件系统。在NiFi的用户界面里,我们可以亲自操刀,动手新建一个数据源,而且,你可以酷炫地选择“HDFS”作为这个新数据源的小马甲,也就是它的类型啦!然后,我们需要输入HDFS的地址、用户名、密码等信息。 4. 创建数据处理流程 最后,我们可以创建一个新的数据处理流程,使Apache NiFi能够读取HDFS中的数据,并对其进行处理和转发。我们可以在NiFi的UI界面中创建新的流程节点,并将它们连接起来。例如,我们可以使用“GetFile”节点来读取HDFS中的数据,使用“TransformJSON”节点来处理数据,使用“PutFile”节点来将处理后的数据保存到其他位置。 三、Apache Beam简介 Apache Beam是一个开源的统一编程模型,它可以用于构建批处理和实时数据处理应用程序。这个东西的好处在于,你可以在各种不同的数据平台上跑同一套代码,这样一来,开发者们就能把更多的精力放在数据处理的核心逻辑上,而不是纠结于那些底层的繁琐细节啦。 四、Hadoop与Apache Beam集成 为了使Hadoop与Apache Beam进行集成,我们需要使用Apache Beam SDK,并将其添加到Hadoop集群中。具体步骤如下: 1. 安装Apache Beam SDK 我们可以从Apache Beam的官方网站下载最新的稳定版本,并按照官方提供的指导手册进行安装。在安装这玩意儿的时候,我们得先调好几个基础配置,就好比Beam的通讯端口、验证登录的方式这些小细节。 2. 将Apache Beam SDK添加到Hadoop集群中 为了让Apache Beam能够访问Hadoop集群中的数据,我们需要配置Beam的环境变量。首先,我们需要确定Hadoop集群的位置,然后在Beam的环境中添加以下参数: javascript export HADOOP_CONF_DIR=/path/to/hadoop/conf export HADOOP_HOME=/path/to/hadoop 3. 编写数据处理代码 接下来,我们可以编写数据处理代码,并使用Apache Beam SDK来运行它。以下是使用Apache Beam SDK处理HDFS中的数据的一个简单示例: java public class HadoopWordCount { public static void main(String[] args) throws Exception { Pipeline p = Pipeline.create(); String input = "gs://dataflow-samples/shakespeare/kinglear.txt"; TextIO.Read read = TextIO.read().from(input); PCollection words = p | read; PCollection> wordCounts = words.apply( MapElements.into(TypeDescriptors.KVs(TypeDescriptors.strings(), TypeDescriptors.longs())) .via((String element) -> KV.of(element, 1)) ); wordCounts.apply(Write.to("gs://my-bucket/output")); p.run(); } } 在这个示例中,我们首先创建了一个名为“p”的Pipeline对象,并指定要处理的数据源。然后,我们使用“TextIO.Read”方法从数据源中读取数据,并将其转换为PCollection类型。接下来,我们要用一个叫“KV.of”的小技巧,把每一条数据都变个身,变成一个个键值对。这个键呢,就是咱们平常说的单词,而对应的值呢,就是一个简简单单的1。就像是给每个单词贴上了一个标记“已出现,记1次”。最后,我们将处理后的数据保存到Google Cloud Storage中的指定位置。 五、结论 总的来说,Hadoop与Apache NiFi和Apache Beam的集成都是非常容易的。只需要按照上述步骤进行操作,并编写相应的数据处理代码即可。而且,你知道吗,Apache NiFi和Apache Beam都超级贴心地提供了灵活度爆棚的API接口,这就意味着我们完全可以按照自己的小心思,随心所欲定制咱们的数据处理流程,就像DIY一样自由自在!相信过不了多久,Hadoop和ETL工具的牵手合作将会在大数据处理圈儿掀起一股强劲风潮,成为大伙儿公认的关键趋势。
2023-06-17 13:12:22
581
繁华落尽-t
转载文章
...法要么很麻烦,比如改配置,要么不稳定,比如文件上G以后,上传要么死掉,要么卡住,通过设置web.config并不能很好的解决这些问题。 这是一个Html5统治浏览器的时代,在这个新的时代,这种问题已被简化并解决,我们可以利用Html5分片上传的技术,那么Plupload则是一个对此技术进行封装的前端脚本库,这个库的好处是可以自动检测浏览器是否支持html5技术,不支持再检测是否支持flash技术,甚至是sliverlight技术,如果支持,就使用检测到的技术。 那么这个库到哪里下载,怎么搭建呢,比较懒的童鞋还是用Install-Package Plupload搞定吧,一个命令搞定所有事 Plupload支持的功能这里就不细说了,什么批量上传,这里我没有用到,主要是感觉它支持的事件非常丰富,文件选取后的事件,文件上传中的事件(可获得文件的上传进度),文件上传成功的事件,文件上传失败的事件,等等 我的例子主要是上传一个单个文件,并显示上传的进度条(使用jQuery的一个进度条插件) 下面的例子主要是为文件上传交给 UploadCoursePackage.ashx 来处理 /ProgressBar/ var progressBar = $("loading").progressbar({ width: '500px', color: 'B3240E', border: '1px solid 000000' }); /Plupload/ //实例化一个plupload上传对象 var uploader = new plupload.Uploader({ browse_button: 'browse', //触发文件选择对话框的按钮,为那个元素id runtimes: 'html5,flash,silverlight,html4',//兼容的上传方式 url: "Handlers/UploadCoursePackage.ashx", //后端交互处理地址 max_retries: 3, //允许重试次数 chunk_size: '10mb', //分块大小 rename: true, //重命名 dragdrop: false, //允许拖拽文件进行上传 unique_names: true, //文件名称唯一性 filters: { //过滤器 max_file_size: '999999999mb', //文件最大尺寸 mime_types: [ //允许上传的文件类型 { title: "Zip", extensions: "zip" }, { title: "PE", extensions: "pe" } ] }, //自定义参数 (键值对形式) 此处可以定义参数 multipart_params: { type: "misoft" }, // FLASH的配置 flash_swf_url: "../Scripts/plupload/Moxie.swf", // Silverligh的配置 silverlight_xap_url: "../Scripts/plupload/Moxie.xap", multi_selection: false //true:ctrl多文件上传, false 单文件上传 }); //在实例对象上调用init()方法进行初始化 uploader.init(); uploader.bind('FilesAdded', function (uploader, files) { $("<%=fileSource.ClientID %>").val(files[0].name); $.ajax( { type: 'post', url: 'HardDiskSpace.aspx/GetHardDiskFreeSpace', data: {}, dataType: 'json', contentType: 'application/json;charset=utf-8', success: function (result) { //选择文件以后检测服务器剩余磁盘空间是否够用 if (files.length > 0) { if (parseInt(files[0].size) > parseInt(result.d)) { $('error-msg').text("文件容量大于剩余磁盘空间,请联系管理员!"); } else { $('error-msg').text(""); } } }, error: function (xhr, err, obj) { $('error-msg').text("检测服务器剩余磁盘空间失败"); } }); }); uploader.bind('UploadProgress', function (uploader, file) { var percent = file.percent; progressBar.progress(percent); }); uploader.bind('FileUploaded', function (up, file, callBack) { var data = $.parseJSON(callBack.response); if (data.statusCode === "1") { $("<%=hfPackagePath.ClientID %>").val(data.filePath); var id = $("<%=hfCourseID.ClientID %>").val(); __doPostBack("save", id); } else { hideLoading(); $('error-msg').text(data.message); } }); uploader.bind('Error', function (up, err) { alert("文件上传失败,错误信息: " + err.message); }); /Plupload/ 后台 UploadCoursePackage.ashx 的代码也重要,主要是文件分片跟不分片的处理方式不一样 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; namespace WebUI.Handlers { /// <summary> /// UploadCoursePackage 的摘要说明 /// </summary> public class UploadCoursePackage : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; int statuscode = 1; string message = string.Empty; string filepath = string.Empty; if (context.Request.Files.Count > 0) { try { string resourceDirectoryName = System.Configuration.ConfigurationManager.AppSettings["resourceDirectory"]; string path = context.Server.MapPath("~/" + resourceDirectoryName); if (!Directory.Exists(path)) Directory.CreateDirectory(path); int chunk = context.Request.Params["chunk"] != null ? int.Parse(context.Request.Params["chunk"]) : 0; //获取当前的块ID,如果不是分块上传的。chunk则为0 string fileName = context.Request.Params["name"]; //这里写的比较潦草。判断文件名是否为空。 string type = context.Request.Params["type"]; //在前面JS中不是定义了自定义参数multipart_params的值么。其中有个值是type:"misoft",此处就可以获取到这个值了。获取到的type="misoft"; string ext = Path.GetExtension(fileName); //fileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), ext); filepath = resourceDirectoryName + "/" + fileName; fileName = Path.Combine(path, fileName); //对文件流进行存储 需要注意的是 files目录必须存在(此处可以做个判断) 根据上面的chunk来判断是块上传还是普通上传 上传方式不一样 ,导致的保存方式也会不一样 FileStream fs = new FileStream(fileName, chunk == 0 ? FileMode.OpenOrCreate : FileMode.Append); //write our input stream to a buffer Byte[] buffer = null; if (context.Request.ContentType == "application/octet-stream" && context.Request.ContentLength > 0) { buffer = new Byte[context.Request.InputStream.Length]; context.Request.InputStream.Read(buffer, 0, buffer.Length); } else if (context.Request.ContentType.Contains("multipart/form-data") && context.Request.Files.Count > 0 && context.Request.Files[0].ContentLength > 0) { buffer = new Byte[context.Request.Files[0].InputStream.Length]; context.Request.Files[0].InputStream.Read(buffer, 0, buffer.Length); } //write the buffer to a file. if (buffer != null) fs.Write(buffer, 0, buffer.Length); fs.Close(); statuscode = 1; message = "上传成功"; } catch (Exception ex) { statuscode = -1001; message = "保存时发生错误,请确保文件有效且格式正确"; Util.LogHelper logger = new Util.LogHelper(); string path = context.Server.MapPath("~/Logs"); logger.WriteLog(ex.Message, path); } } else { statuscode = -404; message = "上传失败,未接收到资源文件"; } string msg = "{\"statusCode\":\"" + statuscode + "\",\"message\":\"" + message + "\",\"filePath\":\"" + filepath + "\"}"; context.Response.Write(msg); } public bool IsReusable { get { return false; } } } } 再附送一个检测服务器端硬盘剩余空间的功能吧 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Script.Services; using System.Web.Services; using System.Web.UI; using System.Web.UI.WebControls; namespace WebUI { public partial class CheckHardDiskFreeSpace : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// 获取磁盘剩余容量 /// </summary> /// <returns></returns> [WebMethod] public static string GetHardDiskFreeSpace() { const string strHardDiskName = @"F:\"; var freeSpace = string.Empty; var drives = DriveInfo.GetDrives(); var myDrive = (from drive in drives where drive.Name == strHardDiskName select drive).FirstOrDefault(); if (myDrive != null) { freeSpace = myDrive.TotalFreeSpace+""; } return freeSpace; } } } 效果展示: 详细配置信息可以参考这篇文章:http://blog.ncmem.com/wordpress/2019/08/12/plupload%e4%b8%8a%e4%bc%a0%e6%95%b4%e4%b8%aa%e6%96%87%e4%bb%b6%e5%a4%b9-2/ 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_45525177/article/details/100654639。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-19 09:43:46
127
转载
转载文章
...显示出来的必要的角色配置。 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
转载
Beego
...text) { c.String(200, "Hello World") }) // 动态添加路由 if len(os.Args) > 1 { path := os.Args[1] router.Get(path, func(c context.Context) { c.String(200, "Welcome to %s", path) }) } // 启动服务器 http.ListenAndServe(":8080", router) } 在这个例子中,如果命令行参数中有参数,那么我们就动态地添加了一个新的路由。这个新的路由是根据命令行参数生成的,所以它是动态的。 四、总结 总的来说,Beego框架中的动态路由是非常强大且灵活的。它可不光能帮我们飞快地搭起那些复杂的应用程序,更能让我们对路由的掌控和管理变得轻松加愉快,就像指挥交通一样得心应手。通过合理的路由设计,我们可以大大提高我们的应用的质量和效率。在接下来的日子,无论是学习还是工作,我真心希望大家能把这些工具和技术玩得溜溜的,让它们发挥出最大的能量,帮助大家创作出更多令人眼前一亮、拍案叫绝的好作品。
2023-04-05 20:57:26
552
林中小径-t
Flink
...e", Types.STRING)); } @Override public void run(SourceContext ctx) throws Exception { for (int i = 0; i < 10; i++) { String value = "value" + i; state.update(value); ctx.collect(value); } } }); 在这个例子中,我们在open方法中创建了一个名为"my-state"的ValueState对象。然后,在run这个方法里头,咱们就不断地给这个状态“刷新”最新的信息,同时把这些新鲜出炉的数值一股脑儿地塞进输出流里去。 三、Flink的容错机制 1. checkpointing checkpointing是Flink的一种容错机制,它可以确保在任务失败后可以从上一次检查点恢复。Flink会在预定义的时间间隔内自动进行checkpoint,也可以通过设置maxConcurrentCheckpoints参数手动控制并发的checkpoint数量。 java env.enableCheckpointing(500); // 每500ms做一次checkpoint 2. savepoint savepoint是另一种Flink的容错机制,它不仅可以保存任务的状态,还可以保存数据的完整图。跟checkpoint不一样的地方在于,savepoint有个大优点:它不会打扰到当前任务的运行。而且你知道吗?恢复savepoint就像按下了快进键,比从checkpoint那里恢复起来速度嗖嗖的,可快多了! java env.getSavepointDirectory(); 四、结论 总的来说,Flink的状态管理和容错机制都是非常强大和灵活的。它们使得Flink能够应对各种复杂的实时和批处理场景。如果你想真正摸透Flink的运行机制,还有它在实际场景中的应用门道,我真心实意地建议你,不妨花点时间钻研一下它的官方文档和教程,保准收获满满!
2023-06-05 11:35:34
462
初心未变-t
JQuery
...之一是支持模块化路由配置,这为构建复杂单页应用提供了更高效便捷的方式。开发人员可以精确控制每个路由对应的组件及数据加载逻辑,并在组件内部通过JavaScript内置API(如window.location)实时监测和操作URL,实现精细化的页面状态管理。 另外,在处理URL参数时,除了原生方法URLSearchParams之外,越来越多的开发者开始采用第三方库如query-string,它提供了更丰富的查询字符串解析和构建功能,尤其适用于处理RESTful API请求中的复杂参数场景。 值得注意的是,尽管AJAX技术极大地改善了用户体验,但过度依赖异步加载也可能影响SEO效果。为此,现代前端框架及服务器端渲染(SSR)技术应运而生,它们可以在服务端生成包含完整数据的HTML,从而让搜索引擎爬虫能够抓取到基于AJAX动态加载的内容所对应的正确URL。 综上所述,掌握URL的获取与解析仅仅是Web开发中URL管理的一部分,随着技术发展和最佳实践的演进,深入理解和运用前沿的路由技术和SEO优化策略,将更好地助力我们应对日益复杂的Web应用程序需求。
2023-02-17 17:07:14
56
红尘漫步_
Golang
...lang在Web应用配置问题上的实践与探讨 1. 引言 Golang,这个由Google开发的高效、简洁且强大的编程语言,在构建高性能Web应用程序时展现了其独特的魅力。然而,在实际编程做项目的过程中,如何妥善处理Web应用的各种配置难题,比如路由咋整、静态文件目录又该怎么管好,这可是每个Go语言开发者都得正面硬刚、必须搞定的重要关卡。本文将深入探讨这些问题,并通过实例代码来阐述解决方案。 2. 路由配置 用Golang打造灵活的URL路由系统 在Golang中,我们通常会使用第三方库如Gin或Echo来实现复杂的路由配置。以Gin为例,它提供了直观且强大的中间件和路由功能: go package main import "github.com/gin-gonic/gin" func main() { r := gin.Default() // 定义一个简单的GET路由 r.GET("/", func(c gin.Context) { c.JSON(200, gin.H{ "message": "Hello, welcome to the home page!", }) }) // 定义带参数的路由 r.GET("/users/:username", func(c gin.Context) { username := c.Param("username") c.String(200, "Hello, %s!", username) }) // 启动服务 r.Run(":8080") } 上述代码展示了如何在Golang中使用Gin框架配置基础的路由规则,包括静态路径("/")和动态路径("/users/:username")。嘿,你知道吗?在这个地方,“:username”其实就是一个神奇的路由参数小能手,它可以在实际的请求过程中,把相应的那部分内容给抓过来,变成一个我们随时可以使用的变量值!就像是个灵活的小助手,在浩瀚的网络请求中为你精准定位并提取关键信息。 3. 静态文件目录 托管静态资源 在Web应用中,静态文件(如HTML、CSS、JavaScript、图片等)的托管也是重要的一环。Gin也提供了方便的方法来设置静态文件目录: go // 添加静态文件目录 r.Static("/static", "./public") // 现在,所有指向 "/static" 的请求都会被映射到 "./public" 目录下的文件 这段代码中,我们设置了"/static"为静态资源的访问路径前缀,而实际的静态文件则存储在项目根目录下的"public"目录中。 4. 深入思考与探讨 处理路由配置和静态文件目录的问题,不仅关乎技术实现,更体现了我们在设计Web架构时的灵活性和预见性。比如说,如果把路由设计得恰到好处,就仿佛给咱们的API铺上了一条宽敞明亮的大道,让咱能轻松梳理、便捷维护。再者,把静态文件资料收拾得井井有条,就像给应用装上了火箭助推器,嗖一下提升运行速度,还能帮服务器大大减压,让它喘口气儿。 当我们在编写Golang Web应用时,务必保持对细节的关注,充分理解并熟练运用各种工具库,这样才能在满足功能需求的同时,打造出既优雅又高效的程序。同时呢,咱们也得不断尝鲜、积极探索新的解决方案。毕竟,技术这家伙可是一直在突飞猛进,指不定啥时候就冒出来个更优秀的法子,让我们的配置策略更加优化、更上一层楼。 总结来说,Golang以其强大而又易用的特性,为我们搭建Web应用提供了一条顺畅的道路。要是咱们能把路由配置得恰到好处,再把静态资源打理得井井有条,那咱们的应用就能更上一层楼,无论多复杂、多变化的业务场景,都能应对自如,让应用表现得更加出色。让我们在实践中不断学习、不断进步,享受Golang带来的开发乐趣吧!
2023-01-10 18:53:06
507
繁华落尽
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
journalctl
- 查看系统日志。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"