這篇文章將為大家詳細講解有關如何使用Redis實現點贊取消點贊,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
/**
*
* @param userId 點贊的人
* @param type 點贊與取消點贊的表示
* @param textId 文章ID
* @param entityUserId -- 被點贊的人,文章作者
*/
private void like(long userId,int type,int textId,long entityUserId){
redisTemplate.execute(new SessionCallback() {
@Override
public Object execute(RedisOperations operations) throws DataAccessException {
String entityLikeKey = RedisKeyUtil.getEntityLikeKey(type, textId);
String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId);
boolean isMember = redisTemplate.opsForSet().isMember(entityLikeKey, userId);
//多個更新操作,需要事務
operations.multi();
if (isMember) {
//取消贊
redisTemplate.opsForSet().remove(entityLikeKey, userId);
redisTemplate.opsForValue().decrement(userLikeKey);
} else {
//點贊
redisTemplate.opsForSet().add(entityLikeKey, userId);
redisTemplate.opsForValue().increment(userLikeKey);
}
return operations.exec();
}
});
}
/**
*查詢某實體(帖子,評論等)點贊數量
* @param type 1點贊,2評論。0表示取消點贊
* @param textId
* @return
*/
private long findEntityLikeCount(int type, int textId){
String entityLikeKey = RedisKeyUtil.getEntityLikeKey(type, textId);
return redisTemplate.opsForSet().size(entityLikeKey);
}
/**
* 查詢某人對某文章的點贊狀態
* @param textId 帖子ID
* @param userId
* @return
*/
private int findEntityLikeStatus(int textId,long userId){
String entityLikeKey = RedisKeyUtil.getEntityLikeKey(1, textId);
//此處返回int,是為了進行擴展。比如擴展踩,為止2.等等情況
return redisTemplate.opsForSet().isMember(entityLikeKey,userId)?1:0;
}
/**
* 查詢某個用戶獲得贊,用于在個人主頁查看收獲了多少贊
* @param userId
* @return
*/
private int findUserLikeCount(long userId){
String userLikeKey = RedisKeyUtil.getUserLikeKey(userId);
Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey);
// count.intValue()數據的整數形式;
return count==null?0:count.intValue();
}Redis–key設置
public class RedisKeyUtil {
private static final String SPLIT = ":";
private static final String PREFIX_ENTITY_LIKE = "like:entity";
private static final String PREFIX_USER_LIKE = "like:user";
private static final String PREFIX_USER_COMMENTS="comments:user";
/**
*某個實體收到的贊,如帖子,
* like:entity:entityType:entityId -> set(userId) 對應set,存入userId
* @param entityType
* @param entityId
* @return
*/
public static String getEntityLikeKey(int entityType, int entityId) {
return PREFIX_ENTITY_LIKE + entityType + SPLIT + entityId;
}
*某個用戶收到的總贊數
* like:user:userId ->long
* @param userId
public static String getUserLikeKey(long userId) {
return PREFIX_USER_LIKE + SPLIT + userId;
* 匯總某個帖子的評論數量
public static String getUserCommentsKey(int articleId) {
return PREFIX_USER_COMMENTS + SPLIT + articleId;關于“如何使用Redis實現點贊取消點贊”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。