对于高并发系统来说,有三个重要的机制来保障其高效运行,它们分别是:缓存、限流和熔断。而缓存是排在最前面也是高并发系统之所以高效运行的关键手段,那么问题来了:缓存只使用 Redis 就够了吗?
当然不是,不要把所有鸡蛋放到一个篮子里,成熟的系统在关键功能实现时一定会考虑冗余设计,注意这里的冗余设计不是贬义词。
冗余设计是在系统或设备完成任务起关键作用的地方,增加一套以上完成相同功能的功能通道(or 系统)、工作元件或部件,以保证当该部分出现故障时,系统或设备仍能正常工作,以减少系统或者设备的故障概率,提高系统可靠性。
例如,飞机的设计,飞机正常运行只需要两个发动机,但在每台飞机的设计中可能至少会设计四个发动机,这就有冗余设计的典型使用场景,这样设计的目的是为了保证极端情况下,如果有一个或两个发动机出现故障,不会因为某个发动机的故障而引起重大的安全事故。
缓存功能的设计也是一样,我们在高并发系统中通常会使用多级缓存来保证其高效运行,其中的多级缓存就包含以下这些:
浏览器缓存:它的实现主要依靠 HTTP 协议中的缓存机制,当浏览器第一次请求一个资源时,服务器会将该资源的相关缓存规则(如 Cache-Control、Expires 等)一同返回给客户端,浏览器会根据这些规则来判断是否需要缓存该资源以及该资源的有效期。
Nginx 缓存:在 Nginx 中配置中开启缓存功能。
分布式缓存:所有系统调用的中间件都是分布式缓存,如 Redis、MemCached 等。
本地缓存:JVM 层面,单系统运行期间在内存中产生的缓存,例如 Caffeine、Google Guava 等。
以下是它们的具体使用。
在 Java Web应用中,实现浏览器缓存可以使用 HttpServletResponse 对象来设置与缓存相关的响应头,以开启浏览器的缓存功能,它的具体实现分为以下几步。
Cache-Control 是 HTTP/1.1 中用于控制缓存策略的主要方式。它可以设置多个指令,如 max-age(定义资源的最大存活时间,单位秒)、no-cache(要求重新验证)、public(指示可以被任何缓存区缓存)、private(只能被单个用户私有缓存存储)等,设置如下:
response.setHeader("Cache-Control","max-age=3600, public");// 缓存一小时
设置一个绝对的过期时间,超过这个时间点后浏览器将不再使用缓存的内容而向服务器请求新的资源,设置如下:
response.setDateHeader("Expires",System.currentTimeMillis()+3600*1000);// 缓存一小时
ETag(实体标签)一种验证机制,它为每个版本的资源生成一个唯一标识符。当客户端发起请求时,会携带上先前接收到的 ETag,服务器根据 ETag 判断资源是否已更新,若未更新则返回 304 Not Modified 状态码,通知浏览器继续使用本地缓存,设置如下:
String etag=generateETagForContent();// 根据内容生成ETagresponse.setHeader("ETag",etag);
指定资源最后修改的时间戳,浏览器下次请求时会带上 If-Modified-Since 头,服务器对比时间戳决定是否返回新内容或发送 304 状态码,设置如下:
long lastModifiedDate=getLastModifiedDate();response.setDateHeader("Last-Modified",lastModifiedDate);
在 Spring Web 框架中,可以通过 HttpServletResponse 对象来设置这些头信息。例如,在过滤器中设置响应头以启用缓存:
publicvoid doFilter(ServletRequest request,ServletResponse response,FilterChainchain)throws IOException,ServletException { HttpServletResponse httpResponse=(HttpServletResponse)response;// 设置缓存策略httpResponse.setHeader("Cache-Control","max-age=3600");// 其他响应头设置...chain.doFilter(request,response);}
以上就是在 Java Web 应用程序中利用 HTTP 协议特性控制浏览器缓存的基本方法。
Nginx 中开启缓存的配置总共有以下 5 步。
在 Nginx 配置中定义一个缓存路径和配置,通过 proxy_cache_path 指令完成,例如,以下配置:
proxy_cache_path/path/to/cache levels=1:2keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
其中:
/path/to/cache:这是缓存文件的存放路径。
levels=1:2:定义缓存目录的层级结构。
keys_zone=my_cache:10m:定义一个名为 my_cache 的共享内存区域,大小为 10MB。
max_size=10g:设置缓存的最大大小为 10GB。
inactive=60m:如果在 60 分钟内没有被访问,缓存将被清理。
use_temp_path=off:避免在文件系统中进行不必要的数据拷贝。
在 server 或 location 块中,使用 proxy_cache 指令来启用缓存,并指定要使用的 keys zone,例如,以下配置:
server {...location/{ proxy_cache my_cache;...} }
使用 proxy_cache_valid 指令来设置哪些响应码的缓存时间,例如,以下配置:
location/{ proxy_cache my_cache;proxy_cache_valid20030412h;proxy_cache_validany1m;...}
确保你已经配置了反向代理,以便 Nginx 可以将请求转发到后端服务器。例如,以下配置:
location / { proxy_pass http://backend_server; ... }
保存并关闭 Nginx 配置文件后,使用 nginx -s reload 命令重新加载配置,使更改生效。
在 Spring Boot 项目中使用注解的方式来操作分布式缓存 Redis 的实现步骤如下。
在你的 pom.xml 文件中添加 Spring Boot 的 Redis 依赖,如下所示:
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency></dependencies>
在 application.properties 或 application.yml 文件中配置 Redis 的相关信息,如下所示。
# application.propertiesspring.redis.host=localhost spring.redis.port=6379
在 Spring Boot 主类或者配置类上添加 @EnableCaching 注解来启用缓存。
importorg.springframework.cache.annotation.EnableCaching;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@EnableCachingpublicclass Application {publicstatic void main(String[]args){ SpringApplication.run(Application.class,args);} }
在服务类或方法上使用 @Cacheable,@CacheEvict,@CachePut 等注解来定义缓存行为。
例如,使用 @Cacheable 注解来缓存方法的返回值:
importorg.springframework.cache.annotation.Cacheable;importorg.springframework.stereotype.Service;@Servicepublicclass UserService {@Cacheable("users")publicUserfindUserById(Long id){// 模拟从数据库中查询用户returnnewUser(id,"Alice");} }
也可以使用 @CacheEvict 注解来删除缓存:
importorg.springframework.cache.annotation.CacheEvict;importorg.springframework.stereotype.Service;@Servicepublicclass UserService {@CacheEvict(value="users",key="#id")publicvoid deleteUser(Long id){// 模拟从数据库中删除用户} }
在这个例子中,deleteUser 方法会删除 "users" 缓存中 key 为 id 的缓存项。
可以使用 @CachePut 注解来更新缓存:
importorg.springframework.cache.annotation.CachePut;importorg.springframework.stereotype.Service;@Servicepublicclass UserService {@CachePut(value="users",key="#user.id")publicUserupdateUser(Useruser){// 模拟更新数据库中的用户信息returnuser;} }
在这个例子中,updateUser 方法会更新 "users" 缓存中 key 为 user.id 的缓存项,缓存的值是方法的返回值。
以 Caffeine 本地缓存的使用为例,它在 Spring Boot 项目中的使用如下。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency><dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId></dependency>
在 application.properties 或 application.yml 文件中配置 Caffeine 缓存的相关参数。例如:
# application.propertiesspring.cache.type=caffeine spring.cache.caffeine.spec=initialCapacity=100,maximumSize=1000,expireAfterWrite=10s
这里 spring.cache.caffeine.spec 是一个 Caffeine 规范字符串,用于设置初始容量、最大容量和写入后过期时间等缓存策略,其中:
initialCapacity:初始容器容量。
maximumSize:最大容量。
expireAfterWrite:写入缓存后 N 长时间后过期。
如果需要更复杂的配置,可以创建一个 Caffeine CacheManager 的配置类:
importcom.github.benmanes.caffeine.cache.Cache;importcom.github.benmanes.caffeine.cache.Caffeine;importorg.springframework.cache.CacheManager;importorg.springframework.cache.annotation.CachingConfigurerSupport;importorg.springframework.cache.interceptor.CacheResolver;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;@Configurationpublicclass CaffeineCacheConfig extends CachingConfigurerSupport {@BeanpublicCacheManager cacheManager(){ Caffeine<Object,Object>caffeine=Caffeine.newBuilder().initialCapacity(100).maximumSize(1000).expireAfterWrite(10,TimeUnit.SECONDS)// 10 秒后过期.recordStats();// 记录缓存统计信息returnnew CaffeineCacheManager("default",caffeine::build);}@OverridepublicCacheResolver cacheResolver(){// 自定义缓存解析器(如果需要)// ...returnsuper.cacheResolver();} }
若要利用 Spring Cache 抽象层,以便通过注解的方式更方便地管理缓存,需要在启动类上添加 @EnableCaching 注解,如下所示:
import org.springframework.cache.annotation.EnableCaching; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
在业务逻辑类中使用 @Cacheable、@CacheEvict 等注解实现数据的缓存读取和更新,和上面分布式缓存的使用相同,具体示例如下:
importorg.springframework.cache.annotation.Cacheable;importorg.springframework.stereotype.Service;@Servicepublicclass UserService {@Cacheable(value="users",key="#id")// 假设我们有一个名为"users"的缓存区域publicUsergetUserById(Long id){// 这里是真实的数据库查询或其他耗时操作returnuserRepository.findById(id).orElse(null);}@CacheEvict(value="users",key="#user.id")publicvoid updateUser(Useruser){ userRepository.save(user);} }
除了以上的缓存之外,还有哪些缓存可以加速程序的执行效率呢?