Spring Cloud中怎么使用redis實(shí)現(xiàn)點(diǎn)贊和取消點(diǎn)贊功能,相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
目前成都創(chuàng)新互聯(lián)已為近1000家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)站空間、網(wǎng)站改版維護(hù)、企業(yè)網(wǎng)站設(shè)計(jì)、科爾沁右翼前網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。
一、Redis 緩存設(shè)計(jì)及實(shí)現(xiàn)
1.1 Redis 安裝及運(yùn)行
Redis 安裝請自行查閱相關(guān)教程。
說下Docker 安裝運(yùn)行 Redis
docker run -d -p 6379:6379 redis:4.0.8
如果已經(jīng)安裝了 Redis,打開命令行,輸入啟動(dòng) Redis 的命令
redis-server
1.2 Redis 與 SpringBoot 項(xiàng)目的整合
1.在 pom.xml 中引入依賴
org.springframework.boot spring-boot-starter-data-redis
2.在啟動(dòng)類上添加注釋 @EnableCaching
@SpringBootApplication @EnableDiscoveryClient @EnableSwagger2 @EnableFeignClients(basePackages = "com.solo.coderiver.project.client") @EnableCaching publicclass UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication.class, args); } }
3.編寫 Redis 配置類 RedisConfig
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import java.net.UnknownHostException; @Configuration publicclass RedisConfig { @Bean @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplateredisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { Jackson2JsonRedisSerializer
至此 Redis 在 SpringBoot 項(xiàng)目中的配置已經(jīng)完成,可以愉快的使用了。
1.3 Redis 的數(shù)據(jù)結(jié)構(gòu)類型
Redis 可以存儲(chǔ)鍵與5種不同數(shù)據(jù)結(jié)構(gòu)類型之間的映射,這5種數(shù)據(jù)結(jié)構(gòu)類型分別為String(字符串)、List(列表)、Set(集合)、Hash(散列)和 Zset(有序集合)。
下面來對這5種數(shù)據(jù)結(jié)構(gòu)類型作簡單的介紹:
1.4 點(diǎn)贊數(shù)據(jù)在 Redis 中的存儲(chǔ)格式
用 Redis 存儲(chǔ)兩種數(shù)據(jù),一種是記錄點(diǎn)贊人、被點(diǎn)贊人、點(diǎn)贊狀態(tài)的數(shù)據(jù),另一種是每個(gè)用戶被點(diǎn)贊了多少次,做個(gè)簡單的計(jì)數(shù)。
由于需要記錄點(diǎn)贊人和被點(diǎn)贊人,還有點(diǎn)贊狀態(tài)(點(diǎn)贊、取消點(diǎn)贊),還要固定時(shí)間間隔取出 Redis 中所有點(diǎn)贊數(shù)據(jù),分析了下 Redis 數(shù)據(jù)格式中 Hash 最合適。
因?yàn)?Hash 里的數(shù)據(jù)都是存在一個(gè)鍵里,可以通過這個(gè)鍵很方便的把所有的點(diǎn)贊數(shù)據(jù)都取出。這個(gè)鍵里面的數(shù)據(jù)還可以存成鍵值對的形式,方便存入點(diǎn)贊人、被點(diǎn)贊人和點(diǎn)贊狀態(tài)。
設(shè)點(diǎn)贊人的 id 為 likedPostId,被點(diǎn)贊人的 id 為 likedUserId ,點(diǎn)贊時(shí)狀態(tài)為 1,取消點(diǎn)贊狀態(tài)為 0。將點(diǎn)贊人 id 和被點(diǎn)贊人 id 作為鍵,兩個(gè) id 中間用 :: 隔開,點(diǎn)贊狀態(tài)作為值。
所以如果用戶點(diǎn)贊,存儲(chǔ)的鍵為:likedUserId::likedPostId,對應(yīng)的值為 1 。取消點(diǎn)贊,存儲(chǔ)的鍵為:likedUserId::likedPostId,對應(yīng)的值為 0 。取數(shù)據(jù)時(shí)把鍵用 :: 切開就得到了兩個(gè)id,也很方便。
在可視化工具 RDM 中看到的是這樣子
1.5 操作 Redis
將具體操作方法封裝到了 RedisService 接口里
RedisService.java
import com.solo.coderiver.user.dataobject.UserLike; import com.solo.coderiver.user.dto.LikedCountDTO; import java.util.List; publicinterface RedisService { /** * 點(diǎn)贊。狀態(tài)為1 * @param likedUserId * @param likedPostId */ void saveLiked2Redis(String likedUserId, String likedPostId); /** * 取消點(diǎn)贊。將狀態(tài)改變?yōu)? * @param likedUserId * @param likedPostId */ void unlikeFromRedis(String likedUserId, String likedPostId); /** * 從Redis中刪除一條點(diǎn)贊數(shù)據(jù) * @param likedUserId * @param likedPostId */ void deleteLikedFromRedis(String likedUserId, String likedPostId); /** * 該用戶的點(diǎn)贊數(shù)加1 * @param likedUserId */ void incrementLikedCount(String likedUserId); /** * 該用戶的點(diǎn)贊數(shù)減1 * @param likedUserId */ void decrementLikedCount(String likedUserId); /** * 獲取Redis中存儲(chǔ)的所有點(diǎn)贊數(shù)據(jù) * @return */ ListgetLikedDataFromRedis(); /** * 獲取Redis中存儲(chǔ)的所有點(diǎn)贊數(shù)量 * @return */ List getLikedCountFromRedis(); }
實(shí)現(xiàn)類 RedisServiceImpl.java
import com.solo.coderiver.user.dataobject.UserLike; import com.solo.coderiver.user.dto.LikedCountDTO; import com.solo.coderiver.user.enums.LikedStatusEnum; import com.solo.coderiver.user.service.LikedService; import com.solo.coderiver.user.service.RedisService; import com.solo.coderiver.user.utils.RedisKeyUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.Cursor; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ScanOptions; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Map; @Service @Slf4j publicclass RedisServiceImpl implements RedisService { @Autowired RedisTemplate redisTemplate; @Autowired LikedService likedService; @Override public void saveLiked2Redis(String likedUserId, String likedPostId) { String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId); redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED, key, LikedStatusEnum.LIKE.getCode()); } @Override public void unlikeFromRedis(String likedUserId, String likedPostId) { String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId); redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED, key, LikedStatusEnum.UNLIKE.getCode()); } @Override public void deleteLikedFromRedis(String likedUserId, String likedPostId) { String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId); redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED, key); } @Override public void incrementLikedCount(String likedUserId) { redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, likedUserId, 1); } @Override public void decrementLikedCount(String likedUserId) { redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, likedUserId, -1); } @Override public ListgetLikedDataFromRedis() { Cursor > cursor = redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_KEY_USER_LIKED, ScanOptions.NONE); List list = new ArrayList<>(); while (cursor.hasNext()){ Map.Entry entry = cursor.next(); String key = (String) entry.getKey(); //分離出 likedUserId,likedPostId String[] split = key.split("::"); String likedUserId = split[0]; String likedPostId = split[1]; Integer value = (Integer) entry.getValue(); //組裝成 UserLike 對象 UserLike userLike = new UserLike(likedUserId, likedPostId, value); list.add(userLike); //存到 list 后從 Redis 中刪除 redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED, key); } return list; } @Override public List getLikedCountFromRedis() { Cursor > cursor = redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, ScanOptions.NONE); List list = new ArrayList<>(); while (cursor.hasNext()){ Map.Entry map = cursor.next(); //將點(diǎn)贊數(shù)量存儲(chǔ)在 LikedCountDT String key = (String)map.getKey(); LikedCountDTO dto = new LikedCountDTO(key, (Integer) map.getValue()); list.add(dto); //從Redis中刪除這條記錄 redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, key); } return list; } }
用到的工具類和枚舉類
RedisKeyUtils, 用于根據(jù)一定規(guī)則生成 key
publicclass RedisKeyUtils { //保存用戶點(diǎn)贊數(shù)據(jù)的key publicstaticfinal String MAP_KEY_USER_LIKED = "MAP_USER_LIKED"; //保存用戶被點(diǎn)贊數(shù)量的key publicstaticfinal String MAP_KEY_USER_LIKED_COUNT = "MAP_USER_LIKED_COUNT"; /** * 拼接被點(diǎn)贊的用戶id和點(diǎn)贊的人的id作為key。格式 222222::333333 * @param likedUserId 被點(diǎn)贊的人id * @param likedPostId 點(diǎn)贊的人的id * @return */ public static String getLikedKey(String likedUserId, String likedPostId){ StringBuilder builder = new StringBuilder(); builder.append(likedUserId); builder.append("::"); builder.append(likedPostId); return builder.toString(); } }
LikedStatusEnum 用戶點(diǎn)贊狀態(tài)的枚舉類
package com.solo.coderiver.user.enums; import lombok.Getter; /** * 用戶點(diǎn)贊的狀態(tài) */ @Getter publicenum LikedStatusEnum { LIKE(1, "點(diǎn)贊"), UNLIKE(0, "取消點(diǎn)贊/未點(diǎn)贊"), ; private Integer code; private String msg; LikedStatusEnum(Integer code, String msg) { this.code = code; this.msg = msg; } }
二、數(shù)據(jù)庫設(shè)計(jì)
數(shù)據(jù)庫表中至少要包含三個(gè)字段:被點(diǎn)贊用戶id,點(diǎn)贊用戶id,點(diǎn)贊狀態(tài)。再加上主鍵id,創(chuàng)建時(shí)間,修改時(shí)間就行了。
建表語句
create table `user_like`( `id` int not null auto_increment, `liked_user_id` varchar(32) not null comment '被點(diǎn)贊的用戶id', `liked_post_id` varchar(32) not null comment '點(diǎn)贊的用戶id', `status` tinyint(1) default'1' comment '點(diǎn)贊狀態(tài),0取消,1點(diǎn)贊', `create_time` timestamp not nulldefault current_timestamp comment '創(chuàng)建時(shí)間', `update_time` timestamp not nulldefault current_timestamp on update current_timestamp comment '修改時(shí)間', primary key(`id`), INDEX `liked_user_id`(`liked_user_id`), INDEX `liked_post_id`(`liked_post_id`) ) comment '用戶點(diǎn)贊表';
對應(yīng)的對象 UserLike
import com.solo.coderiver.user.enums.LikedStatusEnum; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * 用戶點(diǎn)贊表 */ @Entity @Data publicclass UserLike { //主鍵id @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; //被點(diǎn)贊的用戶的id private String likedUserId; //點(diǎn)贊的用戶的id private String likedPostId; //點(diǎn)贊的狀態(tài).默認(rèn)未點(diǎn)贊 private Integer status = LikedStatusEnum.UNLIKE.getCode(); public UserLike() { } public UserLike(String likedUserId, String likedPostId, Integer status) { this.likedUserId = likedUserId; this.likedPostId = likedPostId; this.status = status; } }
三、數(shù)據(jù)庫操作
操作數(shù)據(jù)庫同樣封裝在接口中
LikedService
import com.solo.coderiver.user.dataobject.UserLike; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; publicinterface LikedService { /** * 保存點(diǎn)贊記錄 * @param userLike * @return */ UserLike save(UserLike userLike); /** * 批量保存或修改 * @param list */ ListsaveAll(List list); /** * 根據(jù)被點(diǎn)贊人的id查詢點(diǎn)贊列表(即查詢都誰給這個(gè)人點(diǎn)贊過) * @param likedUserId 被點(diǎn)贊人的id * @param pageable * @return */ Page getLikedListByLikedUserId(String likedUserId, Pageable pageable); /** * 根據(jù)點(diǎn)贊人的id查詢點(diǎn)贊列表(即查詢這個(gè)人都給誰點(diǎn)贊過) * @param likedPostId * @param pageable * @return */ Page getLikedListByLikedPostId(String likedPostId, Pageable pageable); /** * 通過被點(diǎn)贊人和點(diǎn)贊人id查詢是否存在點(diǎn)贊記錄 * @param likedUserId * @param likedPostId * @return */ UserLike getByLikedUserIdAndLikedPostId(String likedUserId, String likedPostId); /** * 將Redis里的點(diǎn)贊數(shù)據(jù)存入數(shù)據(jù)庫中 */ void transLikedFromRedis2DB(); /** * 將Redis中的點(diǎn)贊數(shù)量數(shù)據(jù)存入數(shù)據(jù)庫 */ void transLikedCountFromRedis2DB(); }
LikedServiceImpl 實(shí)現(xiàn)類
import com.solo.coderiver.user.dataobject.UserInfo; import com.solo.coderiver.user.dataobject.UserLike; import com.solo.coderiver.user.dto.LikedCountDTO; import com.solo.coderiver.user.enums.LikedStatusEnum; import com.solo.coderiver.user.repository.UserLikeRepository; import com.solo.coderiver.user.service.LikedService; import com.solo.coderiver.user.service.RedisService; import com.solo.coderiver.user.service.UserService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Slf4j publicclass LikedServiceImpl implements LikedService { @Autowired UserLikeRepository likeRepository; @Autowired RedisService redisService; @Autowired UserService userService; @Override @Transactional public UserLike save(UserLike userLike) { return likeRepository.save(userLike); } @Override @Transactional public ListsaveAll(List list) { return likeRepository.saveAll(list); } @Override public Page getLikedListByLikedUserId(String likedUserId, Pageable pageable) { return likeRepository.findByLikedUserIdAndStatus(likedUserId, LikedStatusEnum.LIKE.getCode(), pageable); } @Override public Page getLikedListByLikedPostId(String likedPostId, Pageable pageable) { return likeRepository.findByLikedPostIdAndStatus(likedPostId, LikedStatusEnum.LIKE.getCode(), pageable); } @Override public UserLike getByLikedUserIdAndLikedPostId(String likedUserId, String likedPostId) { return likeRepository.findByLikedUserIdAndLikedPostId(likedUserId, likedPostId); } @Override @Transactional public void transLikedFromRedis2DB() { List list = redisService.getLikedDataFromRedis(); for (UserLike like : list) { UserLike ul = getByLikedUserIdAndLikedPostId(like.getLikedUserId(), like.getLikedPostId()); if (ul == null){ //沒有記錄,直接存入 save(like); }else{ //有記錄,需要更新 ul.setStatus(like.getStatus()); save(ul); } } } @Override @Transactional public void transLikedCountFromRedis2DB() { List list = redisService.getLikedCountFromRedis(); for (LikedCountDTO dto : list) { UserInfo user = userService.findById(dto.getId()); //點(diǎn)贊數(shù)量屬于無關(guān)緊要的操作,出錯(cuò)無需拋異常 if (user != null){ Integer likeNum = user.getLikeNum() + dto.getCount(); user.setLikeNum(likeNum); //更新點(diǎn)贊數(shù)量 userService.updateInfo(user); } } } }
數(shù)據(jù)庫的操作就這些,主要還是增刪改查。
四、開啟定時(shí)任務(wù)持久化存儲(chǔ)到數(shù)據(jù)庫
定時(shí)任務(wù) Quartz 很強(qiáng)大,就用它了。
Quartz 使用步驟:
1.添加依賴
org.springframework.boot spring-boot-starter-quartz
2.編寫配置文件
package com.solo.coderiver.user.config; import com.solo.coderiver.user.task.LikeTask; import org.quartz.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration publicclass QuartzConfig { privatestaticfinal String LIKE_TASK_IDENTITY = "LikeTaskQuartz"; @Bean public JobDetail quartzDetail(){ return JobBuilder.newJob(LikeTask.class).withIdentity(LIKE_TASK_IDENTITY).storeDurably().build(); } @Bean public Trigger quartzTrigger(){ SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() // .withIntervalInSeconds(10) //設(shè)置時(shí)間周期單位秒 .withIntervalInHours(2) //兩個(gè)小時(shí)執(zhí)行一次 .repeatForever(); return TriggerBuilder.newTrigger().forJob(quartzDetail()) .withIdentity(LIKE_TASK_IDENTITY) .withSchedule(scheduleBuilder) .build(); } }
3.編寫執(zhí)行任務(wù)的類繼承自 QuartzJobBean
package com.solo.coderiver.user.task; import com.solo.coderiver.user.service.LikedService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.time.DateUtils; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.quartz.QuartzJobBean; import java.text.SimpleDateFormat; import java.util.Date; /** * 點(diǎn)贊的定時(shí)任務(wù) */ @Slf4j publicclass LikeTask extends QuartzJobBean { @Autowired LikedService likedService; private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { log.info("LikeTask-------- {}", sdf.format(new Date())); //將 Redis 里的點(diǎn)贊信息同步到數(shù)據(jù)庫里 likedService.transLikedFromRedis2DB(); likedService.transLikedCountFromRedis2DB(); } }
在定時(shí)任務(wù)中直接調(diào)用 LikedService 封裝的方法完成數(shù)據(jù)同步。
看完上述內(nèi)容,你們掌握Spring Cloud中怎么使用Redis實(shí)現(xiàn)點(diǎn)贊和取消點(diǎn)贊功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!