zeromicro / go-zero

A cloud-native Go microservices framework with cli tool for productivity.
https://go-zero.dev
MIT License
29.03k stars 3.93k forks source link

Cache connection test and close #4411

Open kingsley8524267 opened 3 days ago

kingsley8524267 commented 3 days ago

I have checked the related cache issues and documents here, but I have not found how to verify the connection of the cache connection during NewServiceContext to ensure that the configuration connection is correct, and how to close the cache conn?

package svc

import (
    "bookstore/rpc/check/internal/config"
    "bookstore/rpc/model"
    "context"
    "github.com/zeromicro/go-zero/core/stores/sqlx"
)

type ServiceContext struct {
    c     config.Config
    Model model.BookModel // 手动代码
}

func NewServiceContext(c config.Config) (*ServiceContext, error) {
    mysql := sqlx.NewMysql(c.DataSource)

    db, err := mysql.RawDB()
    if err != nil {
        return nil, err
    }

    if err = db.PingContext(context.Background()); err != nil {
        return nil, err
    }

    return &ServiceContext{
        c:     c,
        Model: model.NewBookModel(mysql, c.Cache), // 手动代码
    }, nil
}
MarkJoyMa commented 1 day ago

Set the cache configuration in redis to NonBlock = false, and a redis ping check will be performed when creating the cache.

kingsley8524267 commented 1 day ago

It working! But how to close the cache connection or go-zero will automatically close the cache connection while context done?