面试题答案
一键面试实现思路
- 缓存结构设计:使用一个对象来存储缓存数据,每个缓存项包含数据本身、缓存时间戳。
- 缓存过期检查:在每次从缓存获取数据前,检查当前时间与缓存时间戳的差值是否超过设定的过期时间(如5分钟)。
- HTTP请求处理:在HTTP请求拦截器中处理缓存逻辑,优先从缓存获取数据,若缓存过期则发起新的HTTP请求并更新缓存。
- WebSocket数据更新:当通过WebSocket接收到数据变化通知时,找到对应的缓存项并更新数据及时间戳。
关键代码片段
- 缓存服务
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CacheService {
private cache: { [key: string]: { data: any, timestamp: number } } = {};
private expirationTime = 5 * 60 * 1000; // 5分钟
get(key: string) {
const cached = this.cache[key];
if (cached && Date.now() - cached.timestamp < this.expirationTime) {
return cached.data;
}
return null;
}
set(key: string, data: any) {
this.cache[key] = { data, timestamp: Date.now() };
}
clear(key: string) {
delete this.cache[key];
}
}
- HTTP拦截器
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { CacheService } from './cache.service';
import { finalize } from 'rxjs/operators';
@Injectable()
export class CacheInterceptor implements HttpInterceptor {
constructor(private cacheService: CacheService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const cached = this.cacheService.get(request.url);
if (cached) {
return new Observable(observer => {
observer.next(cached);
observer.complete();
});
}
return next.handle(request).pipe(
finalize(() => {
next.handle(request).subscribe(response => {
this.cacheService.set(request.url, response);
});
})
);
}
}
- WebSocket数据更新处理
import { Component, OnInit } from '@angular/core';
import { CacheService } from './cache.service';
import { WebSocketService } from './websocket.service'; // 假设的WebSocket服务
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private cacheService: CacheService, private webSocketService: WebSocketService) {}
ngOnInit() {
this.webSocketService.dataChange.subscribe(({ url, newData }) => {
this.cacheService.set(url, newData);
});
}
}
假设存在一个WebSocketService
,其dataChange
为一个Observable
,当接收到数据变化通知时,发出包含请求URL和新数据的对象。在应用组件中订阅该Observable
并更新缓存。同时,要在app.module.ts
中注册CacheInterceptor
:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform - browser';
import { AppComponent } from './app.component';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { CacheInterceptor } from './cache.interceptor';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: CacheInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {}