Procházet zdrojové kódy

用户阅读记录异步操作

tianyunperfect před 3 roky
rodič
revize
c514af0855

+ 2 - 0
book-dao/src/main/java/com/book/dao/cps/mapper/UserMapper.java

@@ -24,4 +24,6 @@ public interface UserMapper {
     User selectByOpenId(@Param("openid") String openid);
 
     int updateUserKandian(@Param("user") User user, @Param("kandian") int kandian, @Param("freekandian") int freekandian, @Param("updateTime") int updateTime);
+
+    User selectByUserId(@Param("openId") String userId);
 }

+ 5 - 2
book-dao/src/main/resources/mapper/cps/UserMapper.xml

@@ -65,7 +65,10 @@
     <select id="selectByOpenId" resultMap="BaseResultMap">
       SELECT * from user WHERE openid = #{openid}
     </select>
-    <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
+  <select id="selectByUserId" resultMap="BaseResultMap">
+    SELECT * from user WHERE id = #{userId}
+  </select>
+  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
     delete from user
     where id = #{id,jdbcType=BIGINT}
   </delete>
@@ -368,6 +371,6 @@
   </update>
     <update id="updateUserKandian">
       update user set kandian=#{kandian},free_kandian=#{freekandian},updatetime=#{updateTime}
-      where id=#{user.id} and kandian=#{user.kandian} and free_kandian=#{user.freeKandian}
+      where id=#{user.id} and kandian &gt;= 0 and free_kandian &gt;= 0
     </update>
 </mapper>

+ 2 - 0
book-server/src/main/java/com/book/server/Application.java

@@ -8,11 +8,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.cache.annotation.EnableCaching;
 import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.scheduling.annotation.EnableAsync;
 
 @EnableAspectJAutoProxy(exposeProxy = true)
 @SpringBootApplication
 @Slf4j
 @ComponentScan(basePackages = {"com.book.dao","com.book.server"})
+@EnableAsync
 public class Application implements CommandLineRunner {
     public static void main(String[] args) {
         SpringApplication.run(Application.class);

+ 5 - 1
book-server/src/main/java/com/book/server/annotation/CacheFind.java

@@ -11,5 +11,9 @@ public @interface CacheFind {
     //设定key
     String key();             // 设定key,用户自己设定
 
-    //int seconds() default 0;  //可以指定超时时间,也可以不指定
+    int seconds() default 0;  //可以指定超时时间,也可以不指定
+
+    boolean delete() default false;
+
+    boolean update() default false;
 }

+ 21 - 17
book-server/src/main/java/com/book/server/aspect/CacheAOP.java

@@ -44,27 +44,31 @@ public class CacheAOP {
         try {
             String key = CacheUtil.getKeyWithPre(cacheFind.key(), joinPoint.getArgs());
 
-            Object o = redisUtil.get(key);
-            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
-            Class returnClass = methodSignature.getReturnType();
-
-            //3.校验redis中是否有数据,
-            if (o != null) {
-                result = JsonUtils.getObject(o.toString(), returnClass);
-                return result;
-            }
-            synchronized (key) {
-                Object o1 = redisUtil.get(key);
-                if (o1 != null) {
-                    result = JsonUtils.getObject(o.toString(), returnClass);
-                    return result;
-                }
-                //没缓存,第一次查询数据库
+            if (cacheFind.delete()) {
+                // 删除缓存
+                redisUtil.remove(key);
                 result = joinPoint.proceed(); //执行目标方法
-                //将数据保存到redis
+            } else if (cacheFind.update()) {
+                // 更新缓存
+                result = joinPoint.proceed();
                 redisUtil.setWithTime(key, JsonUtils.toJsonStr(result));
+            } else {
+                // 默认,查询缓存,不存在则set
+                Object o = redisUtil.get(key);
+                MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
+                Class returnClass = methodSignature.getReturnType();
+                //3.校验redis中是否有数据,
+                if (o != null) {
+                    result = JsonUtils.getObject(o.toString(), returnClass);
+                } else {
+                    //没缓存,查询数据库
+                    result = joinPoint.proceed();
+                    //将数据保存到redis
+                    redisUtil.setWithTime(key, JsonUtils.toJsonStr(result));
+                }
             }
             return result;
+
         } catch (Throwable throwable) {
             throwable.printStackTrace();
             throw new RuntimeException(throwable);

+ 6 - 0
book-server/src/main/java/com/book/server/controller/UserController.java

@@ -31,4 +31,10 @@ public class UserController extends BaseController {
         User user = userService.getUserByOpenId(openId);
         return Result.byObject(user);
     }
+    @GetMapping("/getUserByUserId")
+    public Result<User> getUserByUserId(String userId) {
+        User user = userService.getUserByUserId(userId);
+        return Result.byObject(user);
+    }
+
 }

+ 76 - 0
book-server/src/main/java/com/book/server/myevent/AsyncListener.java

@@ -0,0 +1,76 @@
+package com.book.server.myevent;
+
+import com.book.dao.VO.BookContentVO;
+import com.book.dao.cpsshard.entity.UserRecentlyRead;
+import com.book.dao.cpsshard.mapper.UserRecentlyReadMapper;
+import com.book.dao.cpsshard.pojo.example.UserRecentlyReadExample;
+import com.book.dao.utils.DateUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.event.EventListener;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import java.util.concurrent.LinkedBlockingQueue;
+
+@Component
+@Slf4j
+public class AsyncListener {
+
+    @Autowired
+    private UserRecentlyReadMapper userRecentlyReadMapper;
+
+    @EventListener
+    @Async  //异步方法
+    public void updateUserRead(UserRecentReadEvent event) {
+        try {
+            BookContentVO bookContentVO = event.bookContentVO;
+            //尝试更新阅读记录
+            UserRecentlyRead userRecentlyRead = UserRecentlyRead.builder()
+                    .chapterId(bookContentVO.getContentId())
+                    .chapterName(bookContentVO.getContentName())
+                    .updatetime(DateUtils.getNow())
+                    .build();
+            userRecentlyRead.setChapterId(bookContentVO.getContentId());
+            userRecentlyRead.setChapterName(bookContentVO.getContentName());
+            userRecentlyRead.setUpdatetime(DateUtils.getNow());
+            int i = userRecentlyReadMapper.updateByExampleSelective(userRecentlyRead,
+                    UserRecentlyReadExample.newAndCreateCriteria()
+                            .andBookIdEqualTo(bookContentVO.getBookId()).example()
+                    ,
+                    UserRecentlyRead.Column.chapterId,
+                    UserRecentlyRead.Column.chapterName,
+                    UserRecentlyRead.Column.updatetime
+            );
+
+            //如果不存在,则新增
+            if (i <= 0) {
+                userRecentlyReadMapper.insert(UserRecentlyRead.builder()
+                        .userId(bookContentVO.getUserId())
+                        .bookId(bookContentVO.getBookId())
+                        .chapterId(bookContentVO.getContentId())
+                        .chapterName(bookContentVO.getContentName())
+                        .createtime(DateUtils.getNow())
+                        .updatetime(DateUtils.getNow())
+                        .bookShelfAdd((byte) 0)
+                        .bookShelfFlag((byte) 0)
+                        .build());
+            }
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    @EventListener
+    @Async  //异步方法
+    public void testListener(TestEvent event) {
+        try {
+            System.out.println(event.string);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+}

+ 19 - 0
book-server/src/main/java/com/book/server/myevent/TestEvent.java

@@ -0,0 +1,19 @@
+package com.book.server.myevent;
+
+import com.book.dao.VO.BookContentVO;
+import org.springframework.context.ApplicationEvent;
+
+public class TestEvent extends ApplicationEvent {
+    private static final long serialVersionUID = 1L;
+
+    public String string;
+
+    public TestEvent(Object source) {
+        super(source);
+    }
+
+    public TestEvent(Object source, String string) {
+        super(source);
+        this.string = string;
+    }
+}

+ 20 - 0
book-server/src/main/java/com/book/server/myevent/UserRecentReadEvent.java

@@ -0,0 +1,20 @@
+package com.book.server.myevent;
+
+import com.book.dao.VO.BookContentVO;
+import lombok.Data;
+import org.springframework.context.ApplicationEvent;
+
+public class UserRecentReadEvent extends ApplicationEvent {
+    private static final long serialVersionUID = 1L;
+
+    public BookContentVO bookContentVO;
+
+    public UserRecentReadEvent(Object source) {
+        super(source);
+    }
+
+    public UserRecentReadEvent(Object source, BookContentVO bookContentVO) {
+        super(source);
+        this.bookContentVO = bookContentVO;
+    }
+}

+ 7 - 3
book-server/src/main/java/com/book/server/service/CacheService.java

@@ -112,7 +112,7 @@ public class CacheService {
     private UploadBookMapper uploadBookMapper;
 
     @CacheFind(key = "chapters")
-    public List<Chapter> setChaptersByBookIdCache(Long bookId) {
+    public List<Chapter> getChaptersByBookIdCache(Long bookId) {
         List<Chapter> list = new ArrayList<>();
         //如果是本地书籍
         if (isUploadBook(bookId)) {
@@ -121,7 +121,7 @@ public class CacheService {
                             .andBookIdEqualTo(bookId)
                             .example()
             );
-            uploadBooks.forEach(x->{
+            uploadBooks.forEach(x -> {
                 Chapter chapter = new Chapter();
                 chapter.setBookId(x.getBookId().toString());
                 chapter.setContentId(x.getChapterId().toString());
@@ -183,11 +183,15 @@ public class CacheService {
     private UserMapper userMapper;
 
     @CacheFind(key = "user")
-    public User updateUserByIdCache(Long id) {
+    public User getUserByIdCache(Long id) {
         User obj = userMapper.selectByPrimaryKey(id);
         return obj;
     }
 
+    @CacheFind(key = "user", delete = true)
+    public void deleteUserByIdCache(Long id) {
+    }
+
     @CacheFind(key = "searchKeyword")
     public List<SearchKeyword> getSearchKeywordsCache(String sex) {
         SearchKeywordExample example = SearchKeywordExample.newAndCreateCriteria()

+ 2 - 0
book-server/src/main/java/com/book/server/service/UserService.java

@@ -5,4 +5,6 @@ import com.book.dao.cps.pojo.User;
 
 public interface UserService {
     User getUserByOpenId(String openid);
+
+    User getUserByUserId(String userId);
 }

+ 12 - 33
book-server/src/main/java/com/book/server/service/impl/BookServiceImpl.java

@@ -22,6 +22,8 @@ import com.book.server.common.util.JsonUtils;
 import com.book.dao.cps.pojo.example.*;
 import com.book.dao.VO.*;
 import com.book.server.config.Const;
+import com.book.server.myevent.TestEvent;
+import com.book.server.myevent.UserRecentReadEvent;
 import com.book.server.service.BookService;
 import com.book.server.service.CacheService;
 import com.book.server.utils.HttpTool;
@@ -34,6 +36,7 @@ import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationEventPublisher;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.web.multipart.MultipartFile;
@@ -219,7 +222,7 @@ public class BookServiceImpl implements BookService {
         }
 
         //缓存
-        return cacheService.setChaptersByBookIdCache(bookId);
+        return cacheService.getChaptersByBookIdCache(bookId);
     }
 
 
@@ -323,7 +326,7 @@ public class BookServiceImpl implements BookService {
                     // 更新到 user
                     int i = userMapper.updateUserKandian(user, kandian, 0, DateUtils.getNow());
                     checkUpdate(i);
-                    cacheService.updateUserByIdCache(user.getId());
+                    cacheService.deleteUserByIdCache(user.getId());
 
                 } else {
                     return Result.failure(ResultCode.NOMONEY);
@@ -335,39 +338,15 @@ public class BookServiceImpl implements BookService {
         content = getBookContent(bookContentVO);
         // 添加到阅读记录
         if (content != null) {
-            //之前是否读过
-            UserRecentlyRead userRecentlyRead = userRecentlyReadMapper.selectOneByExample(UserRecentlyReadExample.newAndCreateCriteria()
-                    .andUserIdEqualTo(bookContentVO.getUserId())
-                    .andBookIdEqualTo(bookContentVO.getBookId())
-                    .example());
-            if (userRecentlyRead == null) {
-                int i = userRecentlyReadMapper.insert(UserRecentlyRead.builder()
-                        .userId(bookContentVO.getUserId())
-                        .bookId(book.getId())
-                        .chapterId(bookContentVO.getContentId())
-                        .chapterName(bookContentVO.getContentName())
-                        .createtime(DateUtils.getNow())
-                        .updatetime(DateUtils.getNow())
-                        .bookShelfAdd((byte) 0)
-                        .bookShelfFlag((byte) 0)
-                        .build());
-                //checkUpdate(i);
-            } else {
-                userRecentlyRead.setChapterId(bookContentVO.getContentId());
-                userRecentlyRead.setChapterName(bookContentVO.getContentName());
-                userRecentlyRead.setUpdatetime(DateUtils.getNow());
-                int i = userRecentlyReadMapper.updateByPrimaryKeySelective(userRecentlyRead,
-                        UserRecentlyRead.Column.chapterId,
-                        UserRecentlyRead.Column.chapterName,
-                        UserRecentlyRead.Column.updatetime
-                );
-                //checkUpdate(i);
-            }
-
+            applicationEventPublisher.publishEvent(new UserRecentReadEvent(this, bookContentVO));
+            //applicationEventPublisher.publishEvent(new TestEvent(this, "!!!!!!!"));
         }
         return Result.byObject(content);
     }
 
+    @Autowired
+    private ApplicationEventPublisher applicationEventPublisher;
+
     private BookContent getBookContent(BookContentVO bookContentVO) {
         String key = CacheUtil.getKey(Const.EDIT_BOOK_PRE, bookContentVO.getBookId(), bookContentVO.getContentId());
         Object o = redisUtil.get(key);
@@ -387,13 +366,13 @@ public class BookServiceImpl implements BookService {
             } else {
                 bookContent = getBookContentFromRemote(bookContentVO.getBookId(), bookContentVO.getContentId());
             }
+            bookContentVO.setContentName(bookContent.getName());
             redisUtil.setWithTime(key, JsonUtils.toJsonStr(bookContent));
             return bookContent;
         }
     }
 
 
-
     private void checkUpdate(int i) {
         if (i <= 0) {
             throw new RuntimeException("请稍后重试");
@@ -702,7 +681,7 @@ public class BookServiceImpl implements BookService {
     }
 
     public User getUserById(Long id) {
-        return cacheService.updateUserByIdCache(id);
+        return cacheService.getUserByIdCache(id);
     }
 
     private String getUserKey(Long id) {

+ 5 - 0
book-server/src/main/java/com/book/server/service/impl/UserServiceImpl.java

@@ -16,4 +16,9 @@ public class UserServiceImpl implements UserService {
         User user1 = userMapper.selectByOpenId(openid);
         return user1;
     }
+
+    @Override
+    public User getUserByUserId(String userId) {
+        return userMapper.selectByUserId(userId);
+    }
 }