Spring之借助Redis設(shè)計(jì)一個簡單訪問計(jì)數(shù)器的示例
為什么要做一個訪問計(jì)數(shù)?之前的個人博客用得是卜算子做站點(diǎn)訪問計(jì)數(shù),用起來挺好,但出現(xiàn)較多次的響應(yīng)很慢,再其次就是個人博客實(shí)在是訪問太少,數(shù)據(jù)不好看😢…
前面一篇博文簡單介紹了Spring中的RedisTemplate的配置與使用,那么這篇算是一個簡單的應(yīng)用case了,主要基于Redis的計(jì)數(shù)器來實(shí)現(xiàn)統(tǒng)計(jì)
I. 設(shè)計(jì)
一個簡單的訪問計(jì)數(shù)器,主要利用redis的hash結(jié)構(gòu),對應(yīng)的存儲結(jié)構(gòu)如下:
存儲結(jié)構(gòu)比較簡單,為了擴(kuò)展,每個應(yīng)用(or站點(diǎn))對應(yīng)一個APP,然后根據(jù)path路徑進(jìn)行分頁統(tǒng)計(jì),最后有一個特殊的用于統(tǒng)計(jì)全站的訪問計(jì)數(shù)
II. 實(shí)現(xiàn)
主要就是利用Redis的hash結(jié)構(gòu),然后實(shí)現(xiàn)數(shù)據(jù)統(tǒng)計(jì),并沒有太多的難度,Spring環(huán)境下搭建redis環(huán)境可以參考:
1. Redis封裝類
針對幾個常用的做了簡單的封裝,直接使用RedisTemplate的excute方法進(jìn)行的操作,當(dāng)然也是可以使用 template.opsForValue() 等便捷方式,這里采用JSON方式進(jìn)行對象的序列化和反序列化
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; } }
對應(yīng)的配置類
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; } }
2. Controller 支持
首先是定義請求參數(shù):
@Data public class WebCountReqDO implements Serializable { private String appKey; private String referer; }
其次是實(shí)現(xiàn)Controller接口,稍稍注意下,根據(jù)path進(jìn)行計(jì)數(shù)的邏輯:
- 如果請求參數(shù)顯示指定了referer參數(shù),則用傳入的參數(shù)進(jìn)行統(tǒng)計(jì)
- 如果沒有顯示指定referer,則根據(jù)header獲取referer
- 解析referer,分別對path和host進(jìn)行統(tǒng)計(jì)+1,這樣站點(diǎn)的統(tǒng)計(jì)計(jì)數(shù)就是根據(jù)host來的,而頁面的統(tǒng)計(jì)計(jì)數(shù)則是根據(jù)path路徑來的
@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); } } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Spring Security單項(xiàng)目權(quán)限設(shè)計(jì)過程解析
- 設(shè)計(jì)模式在Spring框架中的應(yīng)用匯總
- Spring Boot接口設(shè)計(jì)防篡改、防重放攻擊詳解
- 淺談Spring中如何使用設(shè)計(jì)模式
- 詳解設(shè)計(jì)模式在Spring中的應(yīng)用(9種)
- Spring boot項(xiàng)目中異常攔截設(shè)計(jì)和處理詳解
- 淺談spring中用到的設(shè)計(jì)模式及應(yīng)用場景
- 詳解spring整合shiro權(quán)限管理與數(shù)據(jù)庫設(shè)計(jì)
- 圖解Spring框架的設(shè)計(jì)理念與設(shè)計(jì)模式
- springboot多租戶設(shè)計(jì)過程圖解
相關(guān)文章
淺談Ribbon、Feign和OpenFeign的區(qū)別
這篇文章主要介紹了淺談Ribbon、Feign和OpenFeign的區(qū)別。具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06分析Java非阻塞算法Lock-Free的實(shí)現(xiàn)
非阻塞算法一般會使用CAS來協(xié)調(diào)線程的操作。雖然非阻塞算法有諸多優(yōu)點(diǎn),但是在實(shí)現(xiàn)上要比基于鎖的算法更加繁瑣和負(fù)責(zé)。本文將會介紹兩個是用非阻塞算法實(shí)現(xiàn)的數(shù)據(jù)結(jié)構(gòu)。2021-06-06實(shí)例解析Java的Jackson庫中的數(shù)據(jù)綁定
這篇文章主要介紹了Java的Jackson庫中的數(shù)據(jù)綁定,這里分為通常的簡單數(shù)據(jù)綁定與全數(shù)據(jù)綁定兩種情況來講,需要的朋友可以參考下2016-01-01SpringBoot整合TomCat實(shí)現(xiàn)本地圖片服務(wù)器代碼解析
這篇文章主要介紹了SpringBoot整合TomCat實(shí)現(xiàn)本地圖片服務(wù)器代碼解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08javaweb 實(shí)現(xiàn)文件下載的方法及實(shí)例代碼
這篇文章主要介紹了javaweb 實(shí)現(xiàn)文件下載的方法的相關(guān)資料,這里提供了實(shí)現(xiàn)代碼,需要的朋友可以參考下2016-11-11SpringBoot攔截器excludePathPatterns方法不生效的解決方案
這篇文章主要介紹了SpringBoot攔截器excludePathPatterns方法不生效的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07SpringMVC?bean加載控制的實(shí)現(xiàn)分析
SpringMVC是一種基于Java,實(shí)現(xiàn)了Web?MVC設(shè)計(jì)模式,請求驅(qū)動類型的輕量級Web框架,即使用了MVC架構(gòu)模式的思想,將Web層進(jìn)行職責(zé)解耦?;谡埱篁?qū)動指的就是使用請求-響應(yīng)模型,框架的目的就是幫助我們簡化開發(fā),SpringMVC也是要簡化我們?nèi)粘eb開發(fā)2023-02-02