func (c Topic) getTopics(page int, where string, order string, url string) ([]models.Topic, *Pagination) { if page < 1 { page = 1 url = url[:strings.Index(url, "=")+1] + "1" } var topics []models.Topic var pagination *Pagination if page > models.CachePageSize { // 当前页超出缓存页,从数据库取数据 topics, pagination = c.queryDb(page, where, order, url) } else { // 当前页在缓存中,从缓存中取数据 if err := cache.Get("topics"+url, &topics); err != nil { // 缓存中没有找到,查数据库 topics, pagination = c.queryDb(page, where, order, url) if len(topics) == 0 { return topics, pagination } // 写入缓存 go cache.Set("topics"+url, topics, cache.FOREVER) go cache.Set("pagination"+url, pagination, cache.FOREVER) } else { // 从缓存中取分页 if err := cache.Get("pagination"+url, &pagination); err != nil { revel.ERROR.Println(err) } } } return topics, pagination }
func (c Languages) Show() revel.Result { language := c.Params.Get("language") if language == "" { return c.Redirect(routes.Languages.Index()) } lines, _ := c.Txn.SelectInt("select sum(code + comment + blank) as lines "+ "from files where language = $1", language) var lineStats models.FileStat if err := cache.Get("language-show-linesStats", &lineStats); err != nil { c.Txn.SelectOne(&lineStats, "select sum(code) as code, sum(comment) as comment, "+ "sum(blank) as blank from files where language = $1", language) go cache.Set("language-show-linesStats", lineStats, 30*time.Minute) } var fileCount int64 if err := cache.Get("language-show-fileCount", &fileCount); err != nil { fileCount, _ = c.Txn.SelectInt("select count(*) from files "+ "where language = $1", language) go cache.Set("language-show-fileCount", fileCount, 30*time.Minute) } var repoCount int64 if err := cache.Get("language-show-repoCount", &repoCount); err != nil { repoCount, _ := c.Txn.SelectInt("select count(*) from repos where "+ "language = $1", language) go cache.Set("language-show-repoCount", repoCount, 30*time.Minute) } return c.Render(language, lines, repoCount, fileCount, lineStats) }
// Used to get the list of top languages func (c Languages) Top() revel.Result { type Language struct { Name string Color string } var results []Language limit := 20 if err := cache.Get("languages", &results); err == nil { return c.RenderJson(results) } results = make([]Language, limit) languages, _ := c.Txn.Select(models.RepoStat{}, "select l.language from (select language from files where language != '' "+ "group by language order by count(*) desc limit $1) l order by l.language", limit) colors := [...]string{"#FF0000", "#617C58", "#52D017", "#C0C0C0", "#0000FF", "#808080", "#0000A0", "#ADD8E6", "#FFA500", "#800080", "#A52A2A", "#FFFF00", "#800000", "#00FF00", "#008000", "#FF00FF", "#FF0000", "#57FEFF", "FFA62F", "#8E35EF"} for i := 0; i < len(languages); i++ { results[i] = Language{ Name: languages[i].(*models.RepoStat).Language, Color: colors[i], } } go cache.Set("languages", results, 1*time.Hour) return c.RenderJson(results) }
func CacheWithExpires(key string, target interface{}, loader CacheDataLoader, expires time.Duration) { if err := cache.Get(key, target); err != nil { values := loader(key) setValueToAddress(target, values) cacheKeys = append(cacheKeys, key) go cache.Set(key, values, expires) } }
func TopicsCountCached() (count int) { if err := cache.Get("topics/total", &count); err != nil { if err = db.Model(Topic{}).Count(&count).Error; err == nil { go cache.Set("topics/total", count, 30*time.Minute) } } return }
func RepliesCountCached() (count int) { if err := cache.Get("replies/total", &count); err != nil { if err = db.Model(Reply{}).Count(&count).Error; err == nil { go cache.Set("replies/total", count, 30*time.Minute) } } return }
func (c Product) getProducts() []models.Product { var products []models.Product if err := cache.Get("products", &products); err != nil { c.Engine.Find(&products) go cache.Set("products", products, cache.FOREVER) } return products }
func getCategories() []models.Category { var categories []models.Category if err := cache.Get("categories", &categories); err != nil { xormmodule.Engine.Find(&categories) go cache.Set("categories", categories, cache.FOREVER) } return categories }
func (c Repos) Index() revel.Result { var repoCount int64 var fileCount int64 var userCount int64 var speed int if err := cache.Get("repoCount", &repoCount); err != nil { repoCount, _ = c.Txn.SelectInt("select count(*) from repos") go cache.Set("repoCount", repoCount, 1*time.Hour) } if err := cache.Get("fileCount", &fileCount); err != nil { fileCount, _ = c.Txn.SelectInt("select count(*) from files") go cache.Set("fileCount", fileCount, 1*time.Hour) } if err := cache.Get("userCount", &userCount); err != nil { userCount, _ = c.Txn.SelectInt("select count(distinct(owner)) from repos") go cache.Set("userCount", userCount, 1*time.Hour) } cache.Get("speed", &speed) // lines processed per second return c.Render(repoCount, userCount, fileCount, speed) }
func (c Topic) getReplies(id int64) []models.Reply { var replies []models.Reply str := strconv.Itoa(int(id)) if err := cache.Get("replies"+str, &replies); err != nil { c.Engine.Where("topic_id = ?", id).Find(&replies) go cache.Set("replies"+str, replies, cache.FOREVER) } return replies }
// Method IsInBlocklist is checks against logged out tokens func IsInBlocklist(token string) bool { var existingToken string cache.Get(token, &existingToken) if len(existingToken) > 0 { revel.WARN.Printf("Yes, blocklisted token [%v]", existingToken) return true } return false }
func (c Repos) Stat() revel.Result { limit := 15 var results [][]int var buffer bytes.Buffer var mapResults map[string]interface{} if err := cache.Get("stats", &mapResults); err == nil { return c.RenderJson(mapResults) } languageResults := make([]Language, limit) languages, _ := c.Txn.Select(models.RepoStat{}, "select l.language from (select language from files where language != '' "+ "group by language order by sum(code + comment + blank) desc limit $1) "+ "l order by l.language", limit) colors := [...]string{"#FF0000", "#617C58", "#52D017", "#C0C0C0", "#0000FF", "#808080", "#0000A0", "#ADD8E6", "#FFA500", "#800080", "#A52A2A", "#FFFF00", "#800000", "#00FF00", "#008000", "#FF00FF", "#FF0000", "#57FEFF", "FFA62F", "#8E35EF"} for i := 0; i < len(languages); i++ { languageResults[i] = Language{ Name: languages[i].(*models.RepoStat).Language, Color: colors[i], } buffer.WriteString("'" + languages[i].(*models.RepoStat).Language + "', ") } buffer.WriteString("'" + languages[len(languages)-1].(*models.RepoStat).Language + "'") mapResults = make(map[string]interface{}) mapResults["languages"] = languageResults results = make([][]int, limit) for i := 0; i < len(languages); i++ { repoStats, _ := c.Txn.Select(models.RepoStat{}, "select l.count, l.language from (select sum(code + comment + blank) as count, language "+ "from files where repoid in (select id from repos where language = $1) "+ "and language in ("+buffer.String()+") group by language order by "+ "sum(code + comment + blank) desc) l order by l.language", languages[i].(*models.RepoStat).Language) row := make([]int, limit) for j := 0; j < len(repoStats); j++ { var index int for k := 0; k < limit; k++ { if languageResults[k].Name == repoStats[j].(*models.RepoStat).Language { index = k break } } row[index] = repoStats[j].(*models.RepoStat).Count } results[i] = row } mapResults["stats"] = results go cache.Set("stats", mapResults, 1*time.Hour) return c.RenderJson(mapResults) }
func (c Languages) Index() revel.Result { var dbLineStats []interface{} var dbRepoStats []interface{} lines := 0 if err := cache.Get("dbLineStats", &dbLineStats); err != nil { dbLineStats, _ = c.Txn.Select(models.FileStat{}, "select language, sum(code + comment + blank) as lines "+ "from files group by language order by lines desc") go cache.Set("dbLineStats", dbLineStats, 30*time.Minute) } if err := cache.Get("dbRepoStats", &dbRepoStats); err != nil { dbRepoStats, _ = c.Txn.Select(models.RepoStat{}, "select language, count(*) as count from repos where language != '' "+ "group by language order by count desc") go cache.Set("dbRepoStats", dbRepoStats, 30*time.Minute) } fileStats := make([](*models.FileStat), 15) for i := 0; i < len(dbLineStats); i++ { f := dbLineStats[i].(*models.FileStat) lines += f.Lines if i < 15 { fileStats[i] = dbLineStats[i].(*models.FileStat) } dbLineStats[i].(*models.FileStat).Count = i + 1 } repoStats := make([](*models.RepoStat), 15) var size int if len(repoStats) > len(dbRepoStats) { size = len(dbRepoStats) } else { size = len(repoStats) } for i := 0; i < size; i++ { repoStats[i] = dbRepoStats[i].(*models.RepoStat) } return c.Render(dbLineStats, lines, fileStats, repoStats) }
func GetSetting(key string) (out string) { out = "" if err := cache.Get(settingCacheKey(key), &out); err != nil { s := FindSettingByKey(key) if s.Id <= 0 { db.Save(&s) } out = s.Val s.RewriteCache() } return }
func initRevelTemplateFuncs() { revel.TemplateFuncs["webTitle"] = func(prefix string) (webTitle string) { const KEY = "cache.web.title" if err := cache.Get(KEY, &webTitle); err != nil { webTitle = utils.ForceGetConfig("web.title") go cache.Set(KEY, webTitle, 24*30*time.Hour) } return } revel.TemplateFuncs["logined"] = func(session revel.Session) bool { v, e := session["user"] return e == true && v != "" } }
func (c Admin) SocketConn(token string, ws *websocket.Conn) revel.Result { var access bool user := "" if err := cache.Get(token, &user); err != nil { access = false } else { access = true } cache.Delete(token) if access { subscription := roomevents.Subscribe() defer subscription.Cancel() roomevents.Join(user) defer roomevents.Leave(user) newMessages := make(chan string) go func() { var msg string for { err := websocket.Message.Receive(ws, &msg) if err != nil { close(newMessages) return } newMessages <- msg } }() for { select { case event := <-subscription.New: if websocket.JSON.Send(ws, &event) != nil { // They disconnected. return nil } case msg, ok := <-newMessages: if !ok { return nil } roomevents.Say(user, msg) } } } return nil }
// 帖子详细 func (c Topic) Show(id int64) revel.Result { topic := new(models.Topic) str := strconv.Itoa(int(id)) if err := cache.Get("topic"+str, &topic); err != nil { has, _ := c.Engine.Id(id).Get(topic) if !has { return c.NotFound("帖子不存在") } go cache.Set("topic"+str, topic, cache.FOREVER) } topic.Hits += 1 c.Engine.Id(id).Cols("hits").Update(topic) replies := c.getReplies(id) title := topic.Title return c.Render(title, topic, replies) }
func (c Article) Show(id string) revel.Result { dao, err := model.NewDao() defer dao.Close() if err != nil { c.Response.Status = 500 return c.RenderError(err) } topic := dao.FindTopicById(id) if topic == nil { return c.Redirect("/") } if topic.Status == 0 { return c.RenderTemplate("Article/result.html") } ip := strings.Split(c.Request.RemoteAddr, ":")[0] revel.INFO.Printf("Ip : %s", ip) var obj CacheBean key := fmt.Sprintf("%s.%s", ip, id) err = cache.Get(key, &obj) if err == nil { revel.INFO.Printf("Cache : %v", obj) } else { revel.ERROR.Printf("Cache Errr : %v", err) if !obj.HasCache { obj.HasCache = true go cache.Set(key, obj, 10*time.Minute) topic.Read = topic.Read + 1 dao.UpdateTopic(topic) } } content, ret := utils.GetHTMLContent(id) if ret != nil { c.Response.Status = 500 return c.RenderError(ret) } topic.Body = template.HTML(content) replays, repcnt := dao.GetReplays(id) return c.Render(topic, replays, repcnt) }