I have some golang gin application. Under the hood it launch several goroutines, that execute some sql queries. But some queries are identical. So I decide to use local data cache (within single gin request) I tried using gin context but it doesn't work
type BaseRepository struct {
BaseRepositoryInterface
Db *gorm.DB
Context *gin.Context
}
type CoreWebsiteRepository struct {
*BaseRepository
}
func (repository *CoreWebsiteRepository) GetResourceCenterCityId(websiteId int) (int, error) {
if websiteId == 0 {
return 0, fmt.Errorf("website_id is empty")
}
cacheKeyId := fmt.Sprintf("resource_center_city_id_by_website_id_%d", websiteId)
value, exists := repository.Context.Get(cacheKeyId)
if exists {
return value.(int), nil
}
var data model.CoreWebsite
err := repository.Db.Model(&model.CoreWebsite{}).
Where("website_id = ?", websiteId).
First(&data).
Error
if err != nil {
return 0, err
}
repository.Context.Set(cacheKeyId, data.ResourceCenterCityId)
return data.ResourceCenterCityId, nil
}
But caching doesn't work. I see several lines in the logs (per one gin request):
SELECT * FROM `core_website` WHERE website_id = 1510 ORDER BY `core_website`.`website_id` LIMIT 1
How to properly cache data so that goroutines can exchange them with each other?