ASP.Net F# Redis cache

发布于 2023-11-10 11:59:27 字数 2635 浏览 32 评论 0

Startup.fs 添加 redis cache 配置:

namespace fsharpweb

open fsharpweb.Middlewares
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.Extensions.Configuration
open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Hosting

type Startup(configuration: IConfiguration) =
    member _.Configuration = configuration

    // This method gets called by the runtime. Use this method to add services to the container.
    member _.ConfigureServices(services: IServiceCollection) =
        
        services.AddStackExchangeRedisCache(
            fun opts ->
            opts.Configuration <- "localhost:6379"
            opts.InstanceName <- "sample"
        ) |> ignore
        // Add framework services.
        services.AddControllers() |> ignore

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    member _.Configure(app: IApplicationBuilder, env: IWebHostEnvironment) =
        if (env.IsDevelopment()) then
            app.UseDeveloperExceptionPage() |> ignore
        app.UseRouting()
           .UseMiddleware<LogMiddleWare>()
           .UseAuthorization()
           .UseEndpoints(fun endpoints ->
                endpoints.MapControllers() |> ignore
            ) |> ignore

Cache 操作:

namespace fsharpweb.Controllers

open System
open fsharpweb.FormData
open Microsoft.AspNetCore.Mvc
open Microsoft.Extensions.Logging
open Microsoft.Extensions.Caching.Distributed

[<ApiController>]
[<Route("/")>]
type HomeController (logger : ILogger<HomeController>, cache: IDistributedCache) =
    inherit ControllerBase()

    [<HttpGet>]
    member _.Get() =
        "hello"
        
    [<HttpPost>]
    [<Route("/users/{id}")>]
    member _.Post(id: int, [<FromBody>] body: SignUp) = async {
        let opts = DistributedCacheEntryOptions()
        opts.AbsoluteExpiration <-  DateTimeOffset.Now.AddHours(1.0)
        do! cache.SetStringAsync("kkkk", "hello", opts) |> Async.AwaitTask
        let! data = cache.GetStringAsync("name") |> Async.AwaitTask
        printfn $"{data}"
        return OkObjectResult("hello")
    }

ASP.Net 在 redis 里面实际存储的类型为 Hash 类型,全名 key 为 InstanceName + key 名称,查看 key 具体存储:

127.0.0.1:6379> hgetall samplekkkk
1) "absexp"
2) "-1"
3) "sldexp"
4) "-1"
5) "data"
6) "hello"

值:

127.0.0.1:6379> hvals samplekkkk
1) "-1"
2) "-1"
3) "hello"

查看 TTL:

127.0.0.1:6379> ttl samplekkkk
(integer) 3579

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

文章
评论
27 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文