|
| 1 | +# RedisCache configuration |
| 2 | + |
| 3 | + |
| 4 | +## Configuration to add to the appsettings.json file |
| 5 | + |
| 6 | +```json |
| 7 | +"ConnectionStrings": { |
| 8 | + "Redis": "localhost:6379" |
| 9 | +}, |
| 10 | +"Redis": { |
| 11 | + "InstanceName": "RedisCache_", |
| 12 | + "AbsoluteExpireTime": 60, // in minutes |
| 13 | + "SlidingExpireTime": 15 // in minutes |
| 14 | +} |
| 15 | +``` |
| 16 | + |
| 17 | + |
| 18 | +## Registering services at Startup |
| 19 | + |
| 20 | +```csharp |
| 21 | +public Startup(IConfiguration configuration) |
| 22 | +{ |
| 23 | + Configuration = configuration; |
| 24 | +} |
| 25 | + |
| 26 | +public IConfiguration Configuration { get; } |
| 27 | + |
| 28 | +public void ConfigureServices(IServiceCollection services) |
| 29 | +{ |
| 30 | + services.AddRedisCacheService(Configuration); |
| 31 | +} |
| 32 | +``` |
| 33 | + |
| 34 | + |
| 35 | +## Example of use in a web api controller |
| 36 | +```csharp |
| 37 | +[ApiController] |
| 38 | +[Route("api/[controller]")] |
| 39 | +public class ExampleController : ControllerBase |
| 40 | +{ |
| 41 | + private readonly MyService myService; |
| 42 | + private readonly ICacheService cacheService; |
| 43 | + |
| 44 | + public EmailController(MyService myService, ICacheService cacheService) |
| 45 | + { |
| 46 | + this.cacheService = cacheService; |
| 47 | + this.myService = myService; |
| 48 | + } |
| 49 | + |
| 50 | + [HttpGet] |
| 51 | + public async Task<List<MyListType>> GetMyListTypeAsync() |
| 52 | + { |
| 53 | + logger.LogInformation("GetMyListType"); |
| 54 | + |
| 55 | + var cache = cacheService.GetCache<List<MyListType>>("ListType"); |
| 56 | + |
| 57 | + if (cache != null) |
| 58 | + { |
| 59 | + return cache; |
| 60 | + } |
| 61 | + else |
| 62 | + { |
| 63 | + var result = await myService.GetMyListTypeAsync(); |
| 64 | + return cacheService.SetCache("ListType", result); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | +``` |
0 commit comments