Caching Does Not Appear to Work in Identity Server

2019-06-10 23:09发布

I'm attempting to add caching to our IS4 implementation using their Caching methods. However, my implementation does not appear to be having any impact on the speed of login or the number of queries hitting my database per login (which I would expect caching to reduce both).

The changes I made to implement caching are as follows:

Added the following to Startup.cs ConfigureServices

Updated the services.AddIdenttiyServer() call to include the lines:

.AddInMemoryCaching()
.AddClientStoreCache<IClientStore>()
.AddResourceStoreCache<IResourceStore>()
.AddCorsPolicyCache<ICorsPolicyService>();

Updated ConfigureServices to also have the following:

services.AddScoped<ICorsPolicyService, DefaultCorsPolicyService>();
services.AddScoped<IClientStore, ClientStore>();
services.AddScoped<IResourceStore, ResourceStore>();

That appeared to be the only things I needed to implement, and while the application runs normally, the caching does not seem to be doing anything. What am I missing?

2条回答
姐就是有狂的资本
2楼-- · 2019-06-10 23:44

Basically you need to do 2 things:

First implement the IClientStore:

public class ClientStore : IClientStore
{
    private readonly IClientService clientService;

    public ClientStore(IClientService clientService)
    {
        this.clientService = clientService;
    }

    public Task<Client> FindClientByIdAsync(string clientId)
    {
        var client = this.clientService.GetById(clientId);
        return Task.FromResult(client);
    }
}

The ClientService is my implementation for getting the client from the db, so there you need to put your own.

Then in the Startup.cs you need:

services.AddIdentityServer(options =>
            {
                options.Caching.ClientStoreExpiration = new TimeSpan(0, 5, 0);
            })
            .AddInMemoryCaching()
            .AddClientStoreCache<ClientStore>()
            .// More stuff that you need

This is for the Client Caching but for the Cors and the ResourceStore is quite the same.

I think that you are missing the options.Caching.ClientStoreExpiration part. Start from there.

Hope that this helps.

PS: Forgot to mention - you don't need to explicitly inject your implementation of the IClientStore. By adding it to the .AddClientStoreCache<ClientStore>() it gets injected. But (as in my example) if you have other services, used by the store, you need to inject them.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-06-11 00:04

There is no standard way to cache users.

It caches only:

  1. Clients - AddClientStoreCache
  2. Resources - AddResourceStoreCache
  3. CorsPolicy - AddCorsPolicyCache

More details you can get from documentations

查看更多
登录 后发表回答