文章連接:https://liuyueyi.github.io/hexblog/2018/06/26/180626-Spring之藉助Redis設計一個簡單訪問計數器/java
爲何要作一個訪問計數?以前的我的博客用得是卜算子作站點訪問計數,用起來挺好,但出現較屢次的響應很慢,再其次就是我的博客實在是訪問太少,數據很差看😢...git
前面一篇博文簡單介紹了Spring中的RedisTemplate的配置與使用,那麼這篇算是一個簡單的應用case了,主要基於Redis的計數器來實現統計github
一個簡單的訪問計數器,主要利用redis的hash結構,對應的存儲結構以下:web
存儲結構比較簡單,爲了擴展,每一個應用(or站點)對應一個APP,而後根據path路徑進行分頁統計,最後有一個特殊的用於統計全站的訪問計數redis
主要就是利用Redis的hash結構,而後實現數據統計,並無太多的難度,Spring環境下搭建redis環境能夠參考:spring
針對幾個經常使用的作了簡單的封裝,直接使用RedisTemplate的excute方法進行的操做,固然也是可使用 template.opsForValue()
等便捷方式,這裏採用JSON方式進行對象的序列化和反序列化app
public class QuickRedisClient { private static final Charset CODE = Charset.forName("UTF-8"); private static RedisTemplate<String, String> template; public static void register(RedisTemplate<String, String> template) { QuickRedisClient.template = template; } public static void nullCheck(Object... args) { for (Object obj : args) { if (obj == null) { throw new IllegalArgumentException("redis argument can not be null!"); } } } public static byte[] toBytes(String key) { nullCheck(key); return key.getBytes(CODE); } public static byte[][] toBytes(List<String> keys) { byte[][] bytes = new byte[keys.size()][]; int index = 0; for (String key : keys) { bytes[index++] = toBytes(key); } return bytes; } public static String getStr(String key) { return template.execute((RedisCallback<String>) con -> { byte[] val = con.get(toBytes(key)); return val == null ? null : new String(val); }); } public static void putStr(String key, String value) { template.execute((RedisCallback<Void>) con -> { con.set(toBytes(key), toBytes(value)); return null; }); } public static Long incr(String key, long add) { return template.execute((RedisCallback<Long>) con -> { Long record = con.incrBy(toBytes(key), add); return record == null ? 0L : record; }); } public static Long hIncr(String key, String field, long add) { return template.execute((RedisCallback<Long>) con -> { Long record = con.hIncrBy(toBytes(key), toBytes(field), add); return record == null ? 0L : record; }); } public static <T> T hGet(String key, String field, Class<T> clz) { return template.execute((RedisCallback<T>) con -> { byte[] records = con.hGet(toBytes(key), toBytes(field)); if (records == null) { return null; } return JSON.parseObject(records, clz); }); } public static <T> Map<String, T> hMGet(String key, List<String> fields, Class<T> clz) { List<byte[]> list = template.execute((RedisCallback<List<byte[]>>) con -> con.hMGet(toBytes(key), toBytes(fields))); if (CollectionUtils.isEmpty(list)) { return Collections.emptyMap(); } Map<String, T> result = new HashMap<>(); for (int i = 0; i < fields.size(); i++) { if (list.get(i) == null) { continue; } result.put(fields.get(i), JSON.parseObject(list.get(i), clz)); } return result; } }
對應的配置類學習
package com.git.hui.story.cache.redis; import com.git.hui.story.cache.redis.serializer.DefaultStrSerializer; import org.springframework.cache.CacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisPassword; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; /** * Created by yihui in 18:45 18/6/11. */ @Configuration @PropertySource(value = "classpath:application.yml") public class RedisConf { private final Environment environment; public RedisConf(Environment environment) { this.environment = environment; } @Bean public CacheManager cacheManager() { return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory()).build(); } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, String> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); DefaultStrSerializer serializer = new DefaultStrSerializer(); redisTemplate.setValueSerializer(serializer); redisTemplate.setHashValueSerializer(serializer); redisTemplate.setKeySerializer(serializer); redisTemplate.setHashKeySerializer(serializer); redisTemplate.afterPropertiesSet(); QuickRedisClient.register(redisTemplate); return redisTemplate; } @Bean public RedisConnectionFactory redisConnectionFactory() { LettuceConnectionFactory fac = new LettuceConnectionFactory(); fac.getStandaloneConfiguration().setHostName(environment.getProperty("spring.redis.host")); fac.getStandaloneConfiguration().setPort(Integer.parseInt(environment.getProperty("spring.redis.port"))); fac.getStandaloneConfiguration() .setPassword(RedisPassword.of(environment.getProperty("spring.redis.password"))); fac.afterPropertiesSet(); return fac; } }
首先是定義請求參數:ui
@Data public class WebCountReqDO implements Serializable { private String appKey; private String referer; }
其次是實現Controller接口,稍稍注意下,根據path進行計數的邏輯:this
@Slf4j @RestController @RequestMapping(path = "/count") public class WebCountController { @RequestMapping(path = "cc", method = {RequestMethod.GET}) public ResponseWrapper<CountDTO> addCount(WebCountReqDO webCountReqDO) { String appKey = webCountReqDO.getAppKey(); if (StringUtils.isBlank(appKey)) { return ResponseWrapper.errorReturnMix(Status.StatusEnum.ILLEGAL_PARAMS_MIX, "請指定APPKEY!"); } String referer = ReqInfoContext.getReqInfo().getReferer(); if (StringUtils.isBlank(referer)) { referer = webCountReqDO.getReferer(); } if (StringUtils.isBlank(referer)) { return ResponseWrapper.errorReturnMix(Status.StatusEnum.FAIL_MIX, "沒法獲取請求referer!"); } return ResponseWrapper.successReturn(doUpdateCnt(appKey, referer)); } private CountDTO doUpdateCnt(String appKey, String referer) { try { if (!referer.startsWith("http")) { referer = "https://" + referer; } URI uri = new URI(referer); String host = uri.getHost(); String path = uri.getPath(); long count = QuickRedisClient.hIncr(appKey, path, 1); long total = QuickRedisClient.hIncr(appKey, host, 1); return new CountDTO(count, total); } catch (Exception e) { log.error("get referer path error! referer: {}, e: {}", referer, e); return new CountDTO(1L, 1L); } } }
針對這個簡單的redis計數,目前在我的的mweb和zweb兩個頁面已經接入,在頁腳處能夠看到對應的計數,每次刷新計數會+1
一灰灰的我的博客,記錄全部學習和工做中的博文,歡迎你們前去逛逛
盡信書則不如,已上內容,純屬一家之言,因我的能力有限,不免有疏漏和錯誤之處,如發現bug或者有更好的建議,歡迎批評指正,不吝感激