zeromicro / go-zero

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

Cache connection test and close #4411

Open kingsley8524267 opened 1 month ago

kingsley8524267 commented 1 month 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 month 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 month ago

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