计算机是由硬件和软件组成的复杂系统,以下是计算机各主要部件的组成、功能和性能指标的详细介绍:
一、硬件部分
1. 中央处理器(CPU)
- 功能:是计算机的核心部件,负责执行程序指令,进行算术运算和逻辑运算,控制其他部件协同工作。
- 性能指标
- 主频:CPU的时钟频率,单位是赫兹(Hz),如3.5GHz。主频越高,CPU的运算速度越快,但并不是唯一的性能衡量标准。
- 核心数:现代CPU通常有多个核心,如双核、四核、八核等。核心数越多,同时处理任务的能力越强,适合多任务处理和并行计算。
- 缓存:包括一级缓存(L1)、二级缓存(L2)和三级缓存(L3)。缓存用于暂存CPU频繁访问的数据,减少对内存的访问次数,提高数据读取速度。缓存容量越大,性能越好。
- 指令集:CPU支持的指令集决定了其能够执行的操作类型和效率。例如,x86指令集用于个人计算机,ARM指令集用于移动设备等。
2. 内存储器(内存)
- 功能:用于临时存储CPU正在处理的数据和程序指令,是CPU与外部存储器之间的桥梁,具有读写速度快的特点。
- 性能指标
- 容量:内存容量越大,能够同时存储的数据和程序越多,计算机运行大型软件或多个程序时性能越好。常见的内存容量有4GB、8GB、16GB等。
- 频率:内存的时钟频率,单位是MHz或GHz,如DDR4 3200MHz。频率越高,数据传输速度越快,但需要与CPU和主板支持的频率相匹配。
- 类型:常见的有DDR4、DDR5等。DDR5相比DDR4在带宽、频率和功耗等方面都有显著提升,能够更好地支持高性能计算和图形处理。
3. 存储设备
- 硬盘(HDD)
- 功能:用于长期存储大量数据,如操作系统、软件、文档、图片和视频等。它具有存储容量大、价格相对较低的特点。
- 性能指标
- 容量:常见的硬盘容量有1TB、2TB、4TB等。容量越大,能够存储的数据越多。
- 转速:硬盘的转速通常为5400RPM或7200RPM。转速越高,数据读写速度越快,但也会增加功耗和发热量。
- 缓存:硬盘缓存用于暂存频繁读写的数据,提高数据传输效率。缓存容量一般为64MB、128MB等。
- 固态硬盘(SSD)
- 功能:同样用于数据存储,但采用闪存芯片作为存储介质,具有读写速度快、抗震性强、无噪音等优点,适合对性能要求较高的场景,如系统盘、游戏存储等。
- 性能指标
- 容量:常见的SSD容量有128GB、256GB、512GB、1TB等。随着技术发展,大容量SSD的价格也在逐渐降低。
- 接口类型:常见的有SATA、NVMe等。NVMe接口的SSD采用PCIe通道,数据传输速度远高于SATA接口的SSD,能够显著提升系统启动速度和程序加载速度。
- 读写速度:顺序读写速度和随机读写速度是衡量SSD性能的重要指标。顺序读写速度通常在500MB/s - 7000MB/s之间,随机读写速度则取决于具体的使用场景和存储芯片的质量。
4. 主板
- 功能:是计算机硬件的核心部件,用于连接和协调各个硬件设备的工作,提供电源分配、信号传输和设备管理等功能。
- 性能指标
- 芯片组:芯片组是主板的核心,决定了主板支持的CPU类型、内存类型、扩展接口等。例如,Intel的B系列芯片组主要用于主流桌面电脑,而H系列芯片组则更注重集成显卡性能。
- 扩展接口:包括PCIe插槽、SATA接口、USB接口等。PCIe插槽用于连接显卡、声卡等高速设备;SATA接口用于连接硬盘、光驱等存储设备;USB接口用于连接外设,如键盘、鼠标、U盘等。扩展接口的数量和类型决定了主板的扩展能力和兼容性。
- BIOS/UEFI:BIOS(Basic Input/Output System)或UEFI(Unified Extensible Firmware Interface)是主板上的固件程序,用于初始化硬件设备、检测硬件状态、引导操作系统启动等。现代主板大多采用UEFI,它支持更大的磁盘分区、更灵活的启动选项和更好的硬件管理功能。
5. 显卡(GPU)
- 功能:用于处理计算机的图形输出任务,将数字信号转换为图像或视频信号,驱动显示器显示图像。对于游戏、图形设计、视频编辑等对图形性能要求较高的应用,显卡的作用尤为重要。
- 性能指标
- 核心频率:显卡的核心频率越高,图形处理速度越快,但也会增加功耗和发热量。
- 显存容量:显存用于存储图形数据,如纹理、像素等。显存容量越大,能够处理的图形复杂度越高。常见的显存容量有2GB、4GB、8GB等。
- 显存类型:常见的有GDDR5、GDDR6、HBM等。GDDR6相比GDDR5在带宽和功耗方面有显著提升,HBM则具有更高的集成度和更低的功耗,但成本较高。
- CUDA核心数(对于NVIDIA显卡)或流处理器数(对于AMD显卡):CUDA核心数或流处理器数越多,显卡的并行计算能力越强,能够同时处理更多的图形任务,从而提高图形渲染速度。
6. 电源
- 功能:为计算机各个硬件设备提供稳定的电力供应,确保计算机正常运行。
- 性能指标
- 额定功率:电源的额定功率应根据计算机硬件配置的功耗来选择。例如,一台普通的办公电脑可能只需要300W - 400W的电源,而一台高性能的游戏电脑可能需要600W - 1000W甚至更高的电源功率。
- 转换效率:转换效率越高,电源在将交流电转换为直流电的过程中损耗越小,更加节能。常见的转换效率标准有80 PLUS认证,包括白牌、铜牌、银牌、金牌、白金牌等,其中白金牌的转换效率最高。
- 输出稳定性:电源输出的电压和电流应保持稳定,避免因电压波动或电流不稳定导致硬件损坏。高质量的电源通常具有良好的稳压和滤波功能。
7. 外部设备
- 显示器
- 功能:用于显示计算机输出的图像和视频信息,是用户与计算机交互的重要输出设备。
- 性能指标
- 分辨率:常见的分辨率有1920×1080(全高清)、2560×1440(2K)、3840×2160(4K)等。分辨率越高,显示的图像越清晰、细腻。
- 刷新率:显示器的刷新率表示每秒屏幕刷新的次数,单位是赫兹(Hz)。常见的刷新率有60Hz、144Hz、240Hz等。高刷新率显示器能够减少画面撕裂和卡顿现象,提升游戏和动态画面的显示效果。
- 面板类型:常见的有TN面板、IPS面板和VA面板。TN面板响应速度快,适合游戏;IPS面板色彩还原度高,适合图形设计;VA面板对比度高,适合观看电影。
- 键盘和鼠标
- 功能:键盘用于输入文字和指令,鼠标用于进行图形界面操作,是用户与计算机交互的重要输入设备。
- 性能指标
- 键盘:按键布局、键程、键帽材质等影响键盘的输入体验。机械键盘具有较长的键程和良好的反馈感,适合游戏玩家和打字量较大的用户;薄膜键盘则相对轻薄、价格较低。
- 鼠标:分辨率(DPI)、采样率、按键数量等是衡量鼠标性能的指标。高分辨率鼠标能够更精准地定位,适合游戏和图形设计;多按键鼠标可以设置快捷键,提高工作效率。
二、软件部分
计算机的软件是运行在硬件之上的程序和数据的集合,它赋予计算机各种功能和用途。软件可以分为系统软件和应用软件两大类。
1. 系统软件
- 操作系统(OS)
- 功能:操作系统是计算机硬件与用户之间的接口,负责管理硬件资源、提供用户界面、运行应用程序等。它为应用程序提供运行环境,协调
计算机系统由硬件系统和软件系统两大部分组成,两者协同工作实现数据处理、存储和交互等功能。以下是计算机组成、主要部件功能及性能指标的详细解析:
- 功能:操作系统是计算机硬件与用户之间的接口,负责管理硬件资源、提供用户界面、运行应用程序等。它为应用程序提供运行环境,协调
一、硬件系统:计算机的物理实体
硬件系统是计算机的“躯体”,由五大基本部件构成:运算器、控制器、存储器、输入设备和输出设备。现代计算机中,运算器和控制器集成在CPU中,存储器分为内存储器(内存)和外存储器(硬盘等)。以下是核心部件的功能与性能指标:
1. 中央处理器(CPU)——计算机的“大脑”
- 功能:
- 执行算术运算(如加减乘除)和逻辑运算(如与、或、非)。
- 控制计算机各部件协调工作,读取并执行指令。
- 核心性能指标:
- 核心数/线程数:核心数指CPU内独立运算单元的数量,线程数通过超线程技术实现(如4核8线程)。核心/线程数越多,多任务处理能力越强。
- 主频(GHz):CPU的时钟频率,主频越高,单个核心运算速度越快(如3.6GHz)。
- 缓存(L1/L2/L3):高速存储单元,缓存越大,CPU访问数据的速度越快,减少对内存的依赖。
- 制程工艺(nm):制程越小(如5nm),芯片集成度越高,功耗越低、性能越强(如Intel酷睿i9、AMD锐龙9)。
- 指令集:决定CPU支持的软件类型(如x86、ARM)。
2. 存储器——计算机的“记忆系统”
(1)内存储器(内存)
- 功能:
- 临时存储CPU正在处理的数据和程序,读写速度极快,但断电后数据丢失。
- 性能指标:
- 容量(GB):内存容量越大,可同时运行的程序越多(如16GB、32GB)。
- 频率(MHz):如DDR4-3200,表示内存数据传输速率,频率越高,速度越快。
- 类型:常见DDR4、DDR5(新一代,带宽更高、功耗更低)。
(2)外存储器(硬盘)
- 功能:
- 永久存储数据和程序(如操作系统、文件),断电后数据保留。
- 性能指标:
- 容量(TB/GB):存储数据的总量(如1TB SSD)。
- 类型:
- 机械硬盘(HDD):通过磁头读写,容量大、成本低,但速度慢(常见7200转/分钟)。
- 固态硬盘(SSD):基于闪存颗粒,速度快(读取速度可达500MB/s以上)、抗震性强,但容量相对较小、成本较高。
- NVMe SSD:基于PCIe接口,速度远超普通SSD(如读取速度7000MB/s)。
- 接口类型:SATA(用于HDD/普通SSD)、M.2(用于NVMe SSD)。
3. 显卡(GPU)——图形处理核心
- 功能:
- 负责图像渲染、视频解码等图形处理任务,独立显卡(如NVIDIA RTX 40系列)常用于游戏、设计、AI计算。
- 性能指标:
- 核心架构:如NVIDIA的Ada Lovelace架构、AMD的RDNA 3架构,影响能效比和性能。
- 显存容量(GB):如12GB GDDR6,显存越大,处理高分辨率图形越流畅。
- 显存带宽(GB/s):显存与GPU之间的数据传输速度,带宽越高,图形处理效率越高。
- CUDA核心数(NVIDIA)/流处理器数(AMD):核心数量越多,并行计算能力越强。
4. 主板——硬件连接的“枢纽”
- 功能:
- 提供CPU、内存、显卡、硬盘等部件的插槽和接口,负责数据传输和供电。
- 关键参数:
- 芯片组:如Intel B760、AMD X670,决定支持的CPU型号、内存类型和扩展功能。
- 接口类型:PCIe插槽(用于显卡、NVMe SSD)、SATA接口(用于硬盘)、USB接口等。
- 扩展性:支持多显卡交火(SLI/CFX)、内存超频、存储RAID等功能。
5. 输入/输出设备(I/O设备)
- 输入设备:
- 功能:向计算机输入数据(如键盘、鼠标、摄像头、麦克风)。
- 输出设备:
- 功能:展示计算机处理结果(如显示器、打印机、扬声器)。
- 关键指标(以显示器为例):
- 分辨率:如2560×1440(2K)、3840×2160(4K),分辨率越高,画面越细腻。
- 刷新率(Hz):如144Hz、240Hz,刷新率越高,动态画面越流畅(游戏玩家重点关注)。
- 色域覆盖:如sRGB 100%、DCI-P3 95%,影响色彩表现(设计领域重要)。
6. 电源(PSU)——硬件的“能量源”
- 功能:将交流电转换为计算机硬件所需的直流电(如+12V、+5V)。
- 性能指标:
- 额定功率(W):如500W、850W,需根据CPU、显卡等部件功耗选择(建议预留20%冗余)。
- 认证标准:80 Plus认证(如金牌、白金),认证等级越高,电源转换效率越高(如金牌认证效率≥90%)。
二、软件系统:计算机的“灵魂”
软件系统是控制硬件运行的程序集合,分为系统软件和应用软件:
- 系统软件:管理计算机底层资源,如操作系统(Windows、Linux、macOS)、驱动程序。
- 应用软件:解决具体任务的程序,如办公软件(Office)、设计软件(Photoshop)、游戏程序。
三、性能评估与搭配建议
- 核心硬件搭配原则:
- CPU与主板芯片组兼容(如Intel 13代CPU配B760主板)。
- 显卡性能与显示器分辨率匹配(如4K显示器需RTX 4070及以上显卡)。
- 内存容量根据用途选择:日常办公8-16GB,设计/游戏16-32GB,专业计算32GB+。
- 整机性能测试工具:
- CPU性能:Cinebench R23(多核/单核分数)。
- 显卡性能:3DMark(如Time Spy测试DX12性能)。
- 硬盘速度:CrystalDiskMark(测试读写速度)。
总结
计算机各部件通过协同工作实现复杂功能,性能指标需结合具体使用场景选择。例如,游戏玩家需侧重CPU单核性能、显卡图形能力和高刷新率显示器;办公用户则优先考虑CPU多核效率和大内存;设计/视频剪辑用户需强CPU、大内存和高色域显示器。合理搭配硬件与软件,才能最大化计算机的性能。
Last week I announced the release of Spring Security 3.2 M1 that contains improved Servlet 3 support. In this post, I will introduce some of the more exciting features found in the 3.2 M1 release. Specifically, we will take a look at the following new Spring Security features:
Concurrency Support
Servlet 3 API Integration
Servlet 3 Async Support
Spring MVC Async Integration
Concurrency Support
You might ask “What is concurrency support doing in a release that has a Servlet 3 focused theme?” The reason is that the concurrency support provides a foundation for all the other features found in this release. While the concurrency support is used by the Servlet 3 integration, it can also serve as building blocks to support concurrency and Spring Security in any application. Let’s take a look at Spring Security’s concurrency support now.
DelegatingSecurityContextRunnable
One of the most fundamental building blocks within Spring Security’s concurrency support is the DelegatingSecurityContextRunnable. It wraps a delegate Runnable in order to initialize the SecurityContextHolder with a specified SecurityContext for the delegate. It then invokes the delegate Runnable ensuring to clear the SecurityContextHolder afterwards. The DelegatingSecurityContextRunnable looks something like this:
public void run() {
try {
SecurityContextHolder.setContext(securityContext);
delegate.run();
} finally {
SecurityContextHolder.clearContext();
}
}
While very simple, it makes it seamless to transfer the SecurityContext from one Thread to another. This is important since, in most cases, the SecurityContextHolder acts on a per Thread basis. For example, you might have used Spring Security’s support to secure one of your services. You can now easily transfer the SecurityContext of the current Thread to the Thread that invokes the secured service. An example of how you might do this can be found below:
Runnable originalRunnable = new Runnable() {
public void run() {
// invoke secured service
}
};
SecurityContext context = SecurityContextHolder.getContext();
DelegatingSecurityContextRunnable wrappedRunnable =
new DelegatingSecurityContextRunnable(originalRunnable, context);
new Thread(wrappedRunnable).start();
The code above performs the following steps:
Creates a Runnable that will be invoking our secured service. Notice that it is not aware of Spring Security
Obtains the SecurityContext that we wish to use from the SecurityContextHolder and initializes the DelegatingSecurityContextRunnable
Use the DelegatingSecurityContextRunnable to create a Thread
Start the Thread we created
Since it is quite common to create a DelegatingSecurityContextRunnable with the SecurityContext from the SecurityContextHolder there is a shortcut constructor for it. The following code is the same as the code above:
Runnable originalRunnable = new Runnable() {
public void run() {
// invoke secured service
}
};
DelegatingSecurityContextRunnable wrappedRunnable =
new DelegatingSecurityContextRunnable(originalRunnable);
new Thread(wrappedRunnable).start();
The code we have is simple to use, but it still requires knowledge that we are using Spring Security. In the next section we will take a look at how we can utilize DelegatingSecurityContextExecutor to hide the fact that we are using Spring Security.
DelegatingSecurityContextExecutor
In the previous section, we found that it was easy to use the DelegatingSecurityContextRunnable, but it was not ideal since we had to be aware of Spring Security in order to use it. Let’s take a look at how DelegatingSecurityContextExecutor can shield our code from any knowledge that we are using Spring Security.
The design of DelegatingSecurityContextExecutor is very similar to that of DelegatingSecurityContextRunnable except it accepts a delegate Executor instead of a delegate Runnable. You can see an example of how it might be used below:
SecurityContext context = SecurityContextHolder.createEmptyContext();
Authentication authentication =
new UsernamePasswordAuthenticationToken(“user”,“doesnotmatter”, AuthorityUtils.createAuthorityList(“ROLE_USER”));
context.setAuthentication(authentication);
SimpleAsyncTaskExecutor delegateExecutor =
new SimpleAsyncTaskExecutor();
DelegatingSecurityContextExecutor executor =
new DelegatingSecurityContextExecutor(delegateExecutor, context);
Runnable originalRunnable = new Runnable() {
public void run() {
// invoke secured service
}
};
executor.execute(originalRunnable);
The code performs the following steps:
Creates the SecurityContext to be used for our DelegatingSecurityContextExecutor. Note that in this example we simply create the SecurityContext by hand. However, it does not matter where or how we get the SecurityContext (i.e. we could obtain it from the SecurityContextHolder if we wanted).
Creates a delegateExecutor that is in charge of executing submitted Runnables
Finally we create a DelegatingSecurityContextExecutor which is in charge of wrapping any Runnable that is passed into the execute method with a DelegatingSecurityContextRunnable. It then passes the wrapped Runnable to the delegateExecutor. In this instance, the same SecurityContext will be used for every Runnable submitted to our DelegatingSecurityContextExecutor. This is nice if we are running background tasks that need to be run by a user with elevated privileges.
At this point you may be asking yourself “How does this shield my code of any knowledge of Spring Security?” Instead of creating the SecurityContext and the DelegatingSecurityContextExecutor in our own code, we can inject an already initialized instance of DelegatingSecurityContextExecutor.
@Autowired
private Executor executor; // becomes an instance of our DelegatingSecurityContextExecutor
public void submitRunnable() {
Runnable originalRunnable = new Runnable() {
public void run() {
// invoke secured service
}
};
executor.execute(originalRunnable);
}
Now our code is unaware that the SecurityContext is being propagated to the Thread, then the originalRunnable is executed, and then the SecurityContextHolder is cleared out. In this example, the same user is being used to execute each Thread. What if we wanted to use the user from SecurityContextHolder at the time we invoked executor.execute(Runnable) (i.e. the currently logged in user) to process originalRunnable? This can be done by removing the SecurityContext argument from our DelegatingSecurityContextExecutor constructor. For example:
SimpleAsyncTaskExecutor delegateExecutor = new SimpleAsyncTaskExecutor();
DelegatingSecurityContextExecutor executor =
new DelegatingSecurityContextExecutor(delegateExecutor);
Now anytime executor.execute(Runnable) is executed the SecurityContext is first obtained by the SecurityContextHolder and then that SecurityContext is used to create our DelegatingSecurityContextRunnable. This means that we are executing our Runnable with the same user that was used to invoke the executor.execute(Runnable) code.
Spring Security Concurrency Classes
Refer to the Javadoc for additional integrations with both the Java concurrent APIs and the Spring Task abstractions. They are quite self explanatory once you understand the previous code.
DelegatingSecurityContextCallable
DelegatingSecurityContextExecutor
DelegatingSecurityContextExecutorService
DelegatingSecurityContextRunnable
DelegatingSecurityContextScheduledExecutorService
DelegatingSecurityContextSchedulingTaskExecutor
DelegatingSecurityContextAsyncTaskExecutor
DelegatingSecurityContextTaskExecutor
Servlet 3 API Integration
Spring Security has supported Servlet API integration for quite some time. However, it wasn’t until 3.2 M1 that it supported the new methods added in Servlet 3. In this section we will discuss each of the methods that Spring Security integrates with. If you want to see this in action, you can import Spring Security into Spring Tool Suite using the Gradle Plugin and run servletapi sample application.
HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse)
Spring Security now integrates with HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse). In short, we can use this method to ensure that a user is authenticated. If they are not authenticated, the configured AuthenticationEntryPoint will be used to request the user to authenticate (i.e. redirect to the login page).
HttpServletRequest.login(String,String)
Spring Security now integrates with HttpServletRequest.login(String,String). User’s can utilize this method to authenticate a username and password with Spring Security. If authentication fails, a ServletException that wraps the original Spring Security AuthenticationException will be thrown. This means if you allow the ServletException to propagate Spring Security’s ExceptionTranslationFilter will handle it for you. Alternatively, you can catch the ServletException and handle it yourself.
HttpServletRequest.logout()
Spring Security now integrates with HttpServletRequest.logout() by invoking the configured LogoutHandler implementations. Typically this means that the SecurityContextHolder will be cleared out, the HttpSession will be invalidated, any “Remember Me” authentication will be cleaned up, etc. However, the configured LogoutHandler implementations will vary depending on your Spring Security configuration. It is important to note that after HttpServletRequest.logout() has been invoked, you are still in charge of writing a response out. Typically this would involve a redirect to the welcome page.
AsyncContext.start(Runnable)
The AsynchContext.start(Runnable) method that ensures your credentials will be propagated to the new Thread. Using Spring Security’s newly added concurrency support, Spring Security overrides the AsyncContext.start(Runnable) to ensure that the current SecurityContext is used when processing the Runnable.
Servlet 3 Async Support
Spring Security now supports Servlet 3, Async requests. So how do you use it?
The first step is to ensure you have updated your web.xml to use the 3.0 schema as shown below:
Next you need to ensure that your springSecurityFilterChain is setup for processing asynchronous requests.
springSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy true springSecurityFilterChain /* REQUEST ASYNCThat’s it! Now Spring Security will ensure that your SecurityContext is propagated on asynchronous requests too.
So what has changed? Internal refactoring within Spring Security will ensure that your SecurityContext is no longer cleared out when a response was committed on another Thread, resulting in a user who appeared to be logged out. Additionally, you can use the Spring Security concurrency support and Spring Security’s AsyncContext.start(Runnable) integration to assist you in processing Servlet requests.
Spring MVC Async Integration
Associating SecurityContext to Callable’s
More technically speaking, Spring Security integrates with WebAsyncManager. The SecurityContext that is used to process the Callable is the SecurityContext that exists on the SecurityContextHolder at the time startCallableProcessing is invoked.
As Rossen demonstrated in a previous blog post, Spring Web MVC 3.2 has excellent Servlet 3 Async Support. With no additional configuration, Spring Security will automatically setup the SecurityContext to the Thread that executes a Callable returned by your controllers. For example, the following method will automatically have its Callable executed with the SecurityContext that was available when the Callable was created:
@RequestMapping(method=RequestMethod.POST)
public Callable processUpload(final MultipartFile file) {
return new Callable() {
public Object call() throws Exception {
// …
return “someView”;
}
};
}
There is no automatic integration with a DeferredResult that is returned by controllers. This is because DeferredResult is processed by the users and thus there is no way of automatically integrating with it. However, you can still use Concurrency Support to provide transparent integration with Spring Security.
Feedback Please
I hope this gives you a better understanding of the changes that are available in Spring Security 3.2. M1 and gets you excited for the next milestone. As a member of the community I encourage you to try out the new milestone and report any bugs/enhancements in JIRA. This feedback is a simple, yet very important way to give back to the community!
并发支持
Servlet 3 API集成
Servlet 3异步支持
Spring MVC异步集成
并发支持
您可能会问“在一个以Servlet3为主题的版本中,并发支持在做什么?”原因是并发支持为本版本中的所有其他特征提供了基础。虽然Servlet3集成使用并发支持,但它也可以作为构建块来支持任何应用程序中的并发性和Spring安全性。现在让我们来看看Spring Security的并发支持。
delegatingsecuritycontextunnable
在Spring Security的并发支持中,最基本的构建块之一是delegatingsecuritycontextunnable。它包装可运行的委托,以便使用为该委托指定的SecurityContext初始化SecurityContextHolder。然后,它调用委托Runnable以确保随后清除SecurityContextHolder。delegatingsecuritycontentextrunnable看起来像这样:
公共无效运行(){
试试看{
SecurityContextHolder.setContext(安全上下文);
delegate.run();
}最后{
SecurityContextHolder.clearContext();
}
}
虽然非常简单,但它可以无缝地将SecurityContext从一个线程传输到另一个线程。这一点很重要,因为在大多数情况下,SecurityContextHolder是基于每个线程进行操作的。例如,您可能使用了Spring Security的支持来保护您的一个服务。现在,您可以轻松地将当前线程的SecurityContext传输到调用安全服务的线程。可以在下面找到一个如何执行此操作的示例:
Runnable originalRunnable=new Runnable(){
公共无效运行(){
//调用安全服务
}
};
SecurityContext context=SecurityContextHolder.getContext();
删除安全包含外部不可命名的wrappedRunnable=
新的DelegatingSecurityContextRunnable(originalRunnable,context);
新线程(wrappedRunnable).start();
上面的代码执行以下步骤:
创建将调用我们的安全服务的可运行程序。注意它没有意识到春天的安全
从SecurityContextHolder获取要使用的SecurityContext,并初始化DelegatingSecurityContextUnnable
使用delegatingsecuritycontextunnable创建线程
启动我们创建的线程
由于使用SecurityContextHolder中的SecurityContext创建DelegatingSecurityContextUnnable非常常见,因此有一个快捷构造函数。
Spring Security 3.2 M1(里程碑版本1)是Spring Security框架发展中的一个重要节点,主要亮点是对Servlet 3 API的全面支持。这一支持带来了诸多改进,下面从技术角度进行解析:
1. Servlet 3 API 集成
Spring Security 3.2 M1 首次全面集成了Servlet 3.0规范的新特性,包括异步请求处理、注解配置和原生Filter注册等。
关键改进点:
-
异步请求支持
通过WebAsyncManagerIntegrationFilter
实现对Spring MVC异步处理(如DeferredResult
、Callable
)的安全上下文传递,确保在异步线程中也能保持用户认证状态。 -
原生Servlet 3 Filter注册
支持通过AbstractSecurityWebApplicationInitializer
类以Java代码方式注册Security Filter,替代传统的web.xml
配置,例如:public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { // 自动注册Spring Security的FilterChainProxy }
-
注解驱动配置
引入@EnableWebSecurity
注解,结合WebSecurityConfigurerAdapter
简化Java配置,例如:@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated() .and() .formLogin(); } }
2. CSRF保护增强
Servlet 3支持使得CSRF保护机制更加灵活:
- 默认启用CSRF保护,通过
HttpSessionCsrfTokenRepository
存储CSRF令牌。 - 支持自定义CSRF令牌存储方式(如Redis、JWT),并通过
CsrfTokenRepository
接口集成。 - 对AJAX请求提供更友好的支持,可通过响应头(如
X-CSRF-TOKEN
)传递令牌。
3. SecurityContextHolder策略优化
新增对Servlet 3 AsyncContext
的支持,通过SecurityContextHolder
的MODE_INHERITABLETHREADLOCAL
模式,确保异步处理中安全上下文的正确传递。例如:
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
4. Filter排序与组合
借助Servlet 3的FilterRegistration.Dynamic
,Spring Security能够更精确地控制Filter链的顺序和映射路径,避免与其他Filter冲突。
5. 对Servlet 3容器的要求
- 需运行在Servlet 3.0+容器(如Tomcat 7、Jetty 8+)上。
- 若使用Java配置,需配合Spring 3.2+或Spring 4.0+。
总结
Spring Security 3.2 M1对Servlet 3 API的支持标志着框架向现代化配置和异步处理的转型,减少了对XML的依赖,提升了与Spring MVC的集成度,同时增强了安全性。这些改进为后续版本(如3.2正式版及4.0)奠定了基础,也为开发者提供了更简洁、灵活的安全配置方式。
Spring Security 3.2 M1 是一个重要的里程碑版本,它引入了许多新特性和改进,尤其是在对 Servlet 3 API 的支持方面。以下是 Spring Security 3.2 M1 的主要亮点以及对 Servlet 3 API 支持的详细解析:
Spring Security 3.2 M1 主要亮点
- 并发支持:Spring Security 3.2 M1 引入了并发支持,这为其他特性提供了基础。通过
DelegatingSecurityContextRunnable
等类,Spring Security 能够在多线程环境中无缝传递SecurityContext
,从而确保安全上下文在不同线程之间的一致性。 - Servlet 3 API 集成:Spring Security 现在支持 Servlet 3 中新增的方法,如
HttpServletRequest.authenticate
、HttpServletRequest.login
和HttpServletRequest.logout
。 - Servlet 3 异步支持:Spring Security 现在支持 Servlet 3 的异步请求处理。通过配置
springSecurityFilterChain
,可以确保安全上下文在异步请求中被正确传播。 - Spring MVC 异步集成:Spring Security 自动将
SecurityContext
绑定到执行Callable
的线程中,从而支持 Spring MVC 的异步处理。
Servlet 3 API 支持解析
1. HttpServletRequest.authenticate
Spring Security 集成了 HttpServletRequest.authenticate
方法,用于确保用户已通过身份验证。如果用户未通过身份验证,将调用配置的 AuthenticationEntryPoint
,例如重定向到登录页面。
2. HttpServletRequest.login
Spring Security 支持 HttpServletRequest.login(String username, String password)
方法,用于通过用户名和密码进行身份验证。如果身份验证失败,将抛出一个 ServletException
,其中包含原始的 Spring Security AuthenticationException
。
3. HttpServletRequest.logout
Spring Security 通过调用配置的 LogoutHandler
实现来支持 HttpServletRequest.logout()
方法。这通常会清除 SecurityContextHolder
,使 HttpSession
失效,并清理任何“记住我”的认证信息。
4. AsyncContext.start(Runnable)
Spring Security 覆盖了 AsyncContext.start(Runnable)
方法,以确保当前的 SecurityContext
在处理 Runnable
时被使用。这使得安全上下文能够在异步线程中被正确传播。
配置异步支持
为了启用 Servlet 3 异步支持,需要在 web.xml
中进行以下配置:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</web-app>
同时,需要确保 springSecurityFilterChain
支持异步请求:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ASYNC</dispatcher>
</filter-mapping>
通过这些配置,Spring Security 将确保在异步请求中正确传播 SecurityContext
。
总结
Spring Security 3.2 M1 的发布带来了对 Servlet 3 API 的深度集成和异步请求的支持,这使得 Spring Security 在现代 Web 应用中更加灵活和强大。开发者可以利用这些新特性来构建更加安全和高效的 Web 应用。