用户简介(User Profile)缓存示例

假设我们网站有一个使用多个查询生成的简介页面。我们有此页的模型,如 UserProfile 类,它包含用户所有简介数据,及一个获取指定用户 id 简介的 GetProfile 方法。

  1. public class UserProfile
  2. {
  3. public string Name { get; set; }
  4. public List<CachedFriend> Friends { get; set; }
  5. public List<CachedAlbum> Albums { get; set; }
  6. ...
  7. }
  1. public UserProfile GetProfile(int userID)
  2. {
  3. using (var connection = new SqlConnection("..."))
  4. {
  5. // load profile by userID from DB
  6. }
  7. }

通过使用 LocalCache.Get 方法,我们可以轻松地缓存此信息一小时,并避免每次请求该信息时对数据库进行调用。

  1. public UserProfile GetProfile(int userID)
  2. {
  3. return LocalCache.Get<UserProfile>(
  4. cacheKey: "UserProfile:" + userID,
  5. expiration: TimeSpan.FromHours(1),
  6. loader: delegate {
  7. using (var connection = new SqlConnection("..."))
  8. {
  9. // load profile by userID from DB
  10. }
  11. }
  12. );
  13. }