Selaa lähdekoodia

完善更新缓存

tianyunperfect 3 vuotta sitten
vanhempi
commit
baa3c51b66

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

@@ -7,9 +7,10 @@ import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.cache.annotation.EnableCaching;
 import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
 
+@EnableAspectJAutoProxy(exposeProxy = true)
 @SpringBootApplication
-@EnableCaching
 @Slf4j
 @ComponentScan(basePackages = {"com.book.dao","com.book.server"})
 public class Application implements CommandLineRunner {

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

@@ -10,5 +10,6 @@ import java.lang.annotation.Target;
 public @interface CacheFind {
     //设定key
     String key();             // 设定key,用户自己设定
+
     //int seconds() default 0;  //可以指定超时时间,也可以不指定
 }

+ 8 - 3
book-server/src/main/java/com/book/server/aspect/CacheAOP.java

@@ -1,18 +1,23 @@
 package com.book.server.aspect;
 
 import com.book.server.annotation.CacheFind;
+import com.book.server.utils.JsonUtils;
 import com.book.server.utils.RedisUtil;
+import lombok.extern.slf4j.Slf4j;
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.annotation.Around;
 import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Pointcut;
 import org.aspectj.lang.reflect.MethodSignature;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
+import java.util.ArrayList;
 import java.util.Arrays;
 
 @Component
 @Aspect
+@Slf4j
 public class CacheAOP {
     @Autowired
     private RedisUtil redisUtil;
@@ -44,19 +49,19 @@ public class CacheAOP {
 
             //3.校验redis中是否有数据,
             if (o != null) {
-                result = returnClass.cast(o);
+                result = JsonUtils.getObject(o.toString(), returnClass);
                 return result;
             }
             synchronized (key) {
                 Object o1 = redisUtil.get(key);
                 if (o1 != null) {
-                    result = returnClass.cast(o1);
+                    result = JsonUtils.getObject(o.toString(), returnClass);
                     return result;
                 }
                 //没缓存,第一次查询数据库
                 result = joinPoint.proceed(); //执行目标方法
                 //将数据保存到redis
-                redisUtil.setWithTime(key, result);
+                redisUtil.setWithTime(key, JsonUtils.toJsonStr(result));
             }
             return result;
         } catch (Throwable throwable) {

+ 208 - 0
book-server/src/main/java/com/book/server/service/CacheService.java

@@ -0,0 +1,208 @@
+package com.book.server.service;
+
+import com.book.dao.VO.*;
+import com.book.dao.cps.mapper.*;
+import com.book.dao.cps.pojo.*;
+import com.book.dao.cps.pojo.example.BookCategoryExample;
+import com.book.dao.cps.pojo.example.ManageBlockExample;
+import com.book.dao.cps.pojo.example.SearchKeywordExample;
+import com.book.server.annotation.CacheFind;
+import com.book.server.service.BookService;
+import com.book.server.service.impl.BookServiceImpl;
+import com.book.server.utils.HttpTool;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+
+@Service
+public class CacheService {
+    @Autowired
+    private BookMapper bookMapper;
+    @Autowired
+    private BookCategoryMapper bookCategoryMapper;
+    @Autowired
+    private BookMapper2 bookMapper2;
+
+    @Autowired
+    private ManageBlockMapper manageBlockMapper;
+
+    @Autowired
+    private SearchKeywordMapper searchKeywordMapper;
+    @Autowired
+    private ManageBlockResource2Mapper manageBlockResource2Mapper;
+
+    @Autowired
+    private BookServiceImpl bookService;
+
+    @Autowired
+    private ConfigMapper configMapper;
+
+    @CacheFind(key = "book")
+    public Book getBookById(Long id) {
+        return bookMapper.selectByPrimaryKey(id);
+    }
+
+    @CacheFind(key = "category")
+    public String getCategoryName(Integer id) {
+        List<BookCategory> bookCategories = bookCategoryMapper.selectByExample(BookCategoryExample.newAndCreateCriteria().example());
+        String name = "";
+        for (BookCategory x : bookCategories) {
+            if (x.getId() == id) {
+                name = x.getName();
+            }
+        }
+        return name;
+    }
+
+    @CacheFind(key = "recommend")
+    public List<BookRes> getRecommendFromCache(String sex, int page, int size) {
+        QueryVO queryVO = new QueryVO();
+        queryVO.setSex(sex);
+        queryVO.setPage(page);
+        queryVO.setSize(size);
+        return bookMapper2.novelEndRecommend(queryVO,
+                queryVO.getPage() * queryVO.getSize(), queryVO.getSize());
+    }
+
+    @CacheFind(key = "block")
+    public ArrayList<BlockRes> setBlockByPageIdCache(Integer pageId) {
+        //没有缓存
+        ArrayList<BlockRes> list = new ArrayList<>();
+        // 获取板块
+        ManageBlockExample manageBlockExample = ManageBlockExample.newAndCreateCriteria()
+                .andPageIdEqualTo(pageId)
+                .example();
+        manageBlockExample.orderBy(ManageBlock.Column.weigh.desc());
+        List<ManageBlock> manageBlocks = manageBlockMapper.selectByExample(manageBlockExample);
+
+        // 获取已有版本的所有书籍
+        List<Integer> blockIds = manageBlocks.stream().map(ManageBlock::getId).collect(Collectors.toList());
+        List<ManageBlockResourceRes> blockResourceResList = manageBlockResource2Mapper.getBooks(blockIds);
+
+        // 合并相同 block 书籍
+        HashMap<Integer, TreeSet<ManageBlockResourceRes>> map = new HashMap<>();
+        blockResourceResList.forEach(x -> {
+            TreeSet<ManageBlockResourceRes> set = map.computeIfAbsent(x.getBlockId(), k -> new TreeSet<>((o1, o2) -> o2.getWeigh() - o1.getWeigh()));
+            set.add(x);
+        });
+
+        manageBlocks.forEach(x -> {
+            BlockRes blockRes = new BlockRes();
+            blockRes.setName(x.getName());
+            blockRes.setType(x.getType());
+            blockRes.setSecondName(x.getSecondName());
+            blockRes.setResources(map.getOrDefault(x.getId(), new TreeSet<>()));
+            list.add(blockRes);
+        });
+        return list;
+    }
+
+    @CacheFind(key = "chapters")
+    public List<Chapter> setChaptersByBookIdCache(Long bookId) {
+        List<Chapter> list = new ArrayList<>();
+
+        final String chaptersUrl = "http://new.emeixs.com/index.php/Home/Interface/chapters/bid/" + bookId;
+        String result = HttpTool.sendGet(chaptersUrl, "");
+        if (StringUtils.isEmpty(result)) {
+            return list;
+        }
+        JsonParser parser = new JsonParser();
+        JsonArray jsonArray = parser.parse(result).getAsJsonArray();
+        Book book = getBookById(bookId);
+        if (book == null) {
+            return list;
+        }
+        Integer freeChapterNum = book.getFreeChapterNum();
+
+        if (freeChapterNum == null) {
+            freeChapterNum = 20;
+        }
+        for (int i = 0; i < jsonArray.size(); i++) {
+            JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
+            Chapter chapter = new Chapter();
+            chapter.setReadAble("1");
+            chapter.setBookId(jsonObject.get("book_id").getAsString());
+            chapter.setContentId(jsonObject.get("content_id").getAsString());
+            chapter.setIsPay(jsonObject.get("ispay").getAsString());
+            chapter.setName(jsonObject.get("name").getAsString());
+            chapter.setNum(jsonObject.get("num").getAsString());
+            chapter.setType(jsonObject.get("type").getAsString());
+            chapter.setVolumeId(jsonObject.get("volume_id").getAsString());
+            chapter.setWords(jsonObject.get("words").getAsString());
+            if (i + 1 <= freeChapterNum) {
+                chapter.setReadAble("0");
+            }
+            list.add(chapter);
+        }
+        return list;
+    }
+
+    @CacheFind(key = "bookContent")
+    public BookContent setBookContentCache(Long bookId, long contendId, String contentName) {
+
+        BookContent bookContent;
+        // 修改过的章节
+        String content = bookService.getEditBookContentById(bookId, contendId);
+        if (content != null) {
+            return bookService.getBookContentFromVO(bookId, contendId, contentName, content);
+        }
+
+        if (bookId > 110_0000 && bookId < 110_9999) {
+            // 自定义的书籍
+            bookContent = bookService.getBookContentFromDB(bookId, contendId, contentName);
+        } else {
+            bookContent = bookService.getBookContentFromRemote(bookId, contendId);
+        }
+        return bookContent;
+    }
+
+    @CacheFind(key = "defaultFreeChapterNum")
+    public int setBook_free_chapter_num() {
+        int book_free_chapter_num = Integer.parseInt(configMapper.selectByName("book_free_chapter_num").getValue());
+        return book_free_chapter_num;
+    }
+
+    @Autowired
+    private UserMapper userMapper;
+
+    @CacheFind(key = "user")
+    public User updateUserByIdCache(Long id) {
+        User obj = userMapper.selectByPrimaryKey(id);
+        return obj;
+    }
+
+    @CacheFind(key = "searchKeyword")
+    public List<SearchKeyword> getSearchKeywordsCache(String sex) {
+        SearchKeywordExample example = SearchKeywordExample.newAndCreateCriteria()
+                .andSexEqualTo(sex)
+                .example();
+        example.orderBy(SearchKeyword.Column.weigh.desc());
+        List<SearchKeyword> searchKeywords = searchKeywordMapper.selectByExample(example);
+        return searchKeywords;
+    }
+
+    @CacheFind(key = "smartRecommand")
+    public List<BookRes> setSmartRecommandCache(String sex) {
+        QueryVO queryVO = new QueryVO();
+        queryVO.setSex(sex);
+        List<BookRes> bookRes = bookMapper2.smartRecommand(queryVO);
+        return bookRes;
+    }
+
+    @CacheFind(key = "topRecommend")
+    public List<BookRes> setTopRecommendCache(String sex) {
+        QueryVO queryVO = new QueryVO();
+        queryVO.setSex(sex);
+        List<BookRes> bookRes = bookMapper2.topRecommend(queryVO, 0, 20);
+        return bookRes;
+    }
+}

+ 34 - 292
book-server/src/main/java/com/book/server/service/impl/BookServiceImpl.java

@@ -14,6 +14,7 @@ import com.book.dao.cpsshard.mapper.UserRecentlyReadMapper;
 import com.book.dao.cpsshard.pojo.example.ConsumeExample;
 import com.book.dao.cpsshard.pojo.example.RechargeExample;
 import com.book.dao.cpsshard.pojo.example.UserRecentlyReadExample;
+import com.book.server.annotation.CacheFind;
 import com.book.server.common.entity.Result;
 import com.book.server.common.entity.ResultCode;
 import com.book.server.common.util.DateUtils;
@@ -21,18 +22,17 @@ import com.book.server.common.util.JsonUtils;
 import com.book.dao.cps.pojo.example.*;
 import com.book.dao.VO.*;
 import com.book.server.service.BookService;
+import com.book.server.service.CacheService;
 import com.book.server.utils.HttpTool;
 import com.book.server.utils.RedisUtil;
 import com.google.gson.JsonArray;
 import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
 import com.google.gson.JsonParser;
+import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.web.multipart.MultipartFile;
@@ -45,18 +45,18 @@ import java.util.*;
 import java.util.stream.Collectors;
 
 @Service
+@Slf4j
 public class BookServiceImpl implements BookService {
-    public static final Logger logger = LoggerFactory.getLogger(BookServiceImpl.class);
     @Autowired
     private BookMapper bookMapper;
     @Autowired
     private BookMapper2 bookMapper2;
+    @Autowired
+    private CacheService cacheService;
 
     @Autowired
     private ManageBlockMapper manageBlockMapper;
 
-    @Autowired
-    private ManageBlockResourceMapper manageBlockResourceMapper;
     @Autowired
     private BookCategoryMapper bookCategoryMapper;
     @Autowired
@@ -64,6 +64,7 @@ public class BookServiceImpl implements BookService {
     @Autowired
     private ManageBlockResource2Mapper manageBlockResource2Mapper;
 
+
     public List<BookCategory> getAllCategory() {
         List<BookCategory> bookCategories = bookCategoryMapper.selectByExample(
                 BookCategoryExample.newAndCreateCriteria().example()
@@ -76,8 +77,8 @@ public class BookServiceImpl implements BookService {
     public List<BookRes> query(QueryVO queryVO) {
         List<BookRes> bookResList = new ArrayList<>();
         if (queryVO.getBookId() != null) {
-            Book bookById = getBookById(queryVO.getBookId());
-            String categoryName = getCategoryName(bookById.getBookCategoryId());
+            Book bookById = cacheService.getBookById(queryVO.getBookId());
+            String categoryName = cacheService.getCategoryName(bookById.getBookCategoryId());
             BookRes bookRes = new BookRes();
             BeanUtils.copyProperties(bookById, bookRes);
             bookRes.setCategoryName(categoryName);
@@ -95,76 +96,16 @@ public class BookServiceImpl implements BookService {
         if (queryVO.getPage() == 5) {
             return bookRes;
         }
-        return getRecommendFromCache(queryVO);
+        return cacheService.getRecommendFromCache(queryVO.getSex(), queryVO.getPage(), queryVO.getSize());
     }
 
-    public List<BookRes> getRecommendFromCache(QueryVO queryVO) {
-        String key = getKey("recommend", queryVO.getSex(), queryVO.getPage(), queryVO.getSize());
-        Object o = redisUtil.get(key);
-        if (o == null) {
-            return setRecommendCache(key, queryVO);
-        } else {
-            return (List<BookRes>) o;
-        }
-    }
-
-    public synchronized List<BookRes> setRecommendCache(String key, QueryVO queryVO) {
-        Object o = redisUtil.get(key);
-        if (o != null) {
-            return (List<BookRes>) o;
-        }
-        List<BookRes> books = bookMapper2.novelEndRecommend(queryVO,
-                queryVO.getPage() * queryVO.getSize(), queryVO.getSize());
-        redisUtil.setWithTime(key, books);
-        return books;
-    }
 
     @Override
     public List<BlockRes> getBlockByPageId(Integer pageId) {
-        ArrayList<BlockRes> list = setBlockByPageIdCache(pageId);
+        ArrayList<BlockRes> list = cacheService.setBlockByPageIdCache(pageId);
         return list;
     }
 
-    private synchronized ArrayList<BlockRes> setBlockByPageIdCache(Integer pageId) {
-        //缓存
-        String key = getKey("block", pageId.toString());
-        Object o = redisUtil.get(key);
-        if (o != null) {
-            return (ArrayList<BlockRes>) o;
-        }
-        //没有缓存
-        ArrayList<BlockRes> list = new ArrayList<>();
-        // 获取板块
-        ManageBlockExample manageBlockExample = ManageBlockExample.newAndCreateCriteria()
-                .andPageIdEqualTo(pageId)
-                .example();
-        manageBlockExample.orderBy(ManageBlock.Column.weigh.desc());
-        List<ManageBlock> manageBlocks = manageBlockMapper.selectByExample(manageBlockExample);
-
-        // 获取已有版本的所有书籍
-        List<Integer> blockIds = manageBlocks.stream().map(ManageBlock::getId).collect(Collectors.toList());
-        List<ManageBlockResourceRes> blockResourceResList = manageBlockResource2Mapper.getBooks(blockIds);
-
-        // 合并相同 block 书籍
-        HashMap<Integer, TreeSet<ManageBlockResourceRes>> map = new HashMap<>();
-        blockResourceResList.forEach(x -> {
-            TreeSet<ManageBlockResourceRes> set = map.computeIfAbsent(x.getBlockId(), k -> new TreeSet<>((o1, o2) -> o2.getWeigh() - o1.getWeigh()));
-            set.add(x);
-        });
-
-        manageBlocks.forEach(x -> {
-            BlockRes blockRes = new BlockRes();
-            blockRes.setName(x.getName());
-            blockRes.setType(x.getType());
-            blockRes.setSecondName(x.getSecondName());
-            blockRes.setResources(map.getOrDefault(x.getId(), new TreeSet<>()));
-            list.add(blockRes);
-        });
-        redisUtil.setWithTime(key, list);
-        return list;
-    }
-
-
     @Override
     public void insertBooks() {
 
@@ -277,125 +218,35 @@ public class BookServiceImpl implements BookService {
         }
 
         //缓存
-        String key = getKey("chapters", bookId);
-        Object o = redisUtil.get(key);
-        if (o != null) {
-            return (List<Chapter>) o;
-        } else {
-            return setChaptersByBookIdCache(key, bookId);
-        }
+        return cacheService.setChaptersByBookIdCache(bookId);
     }
 
-    private synchronized List<Chapter> setChaptersByBookIdCache(String key, Long bookId) {
-        Object o = redisUtil.get(key);
-        if (o != null) {
-            return (List<Chapter>) o;
-        }
-
-        List<Chapter> list = new ArrayList<>();
-
-        final String chaptersUrl = "http://new.emeixs.com/index.php/Home/Interface/chapters/bid/" + bookId;
-        String result = HttpTool.sendGet(chaptersUrl, "");
-        if (StringUtils.isEmpty(result)) {
-            return list;
-        }
-        JsonParser parser = new JsonParser();
-        JsonArray jsonArray = parser.parse(result).getAsJsonArray();
-        Book book = getBookById(bookId);
-        if (book == null) {
-            return list;
-        }
-        Integer freeChapterNum = book.getFreeChapterNum();
-
-        if (freeChapterNum == null) {
-            freeChapterNum = 20;
-        }
-        for (int i = 0; i < jsonArray.size(); i++) {
-            JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
-            Chapter chapter = new Chapter();
-            chapter.setReadAble("1");
-            chapter.setBookId(jsonObject.get("book_id").getAsString());
-            chapter.setContentId(jsonObject.get("content_id").getAsString());
-            chapter.setIsPay(jsonObject.get("ispay").getAsString());
-            chapter.setName(jsonObject.get("name").getAsString());
-            chapter.setNum(jsonObject.get("num").getAsString());
-            chapter.setType(jsonObject.get("type").getAsString());
-            chapter.setVolumeId(jsonObject.get("volume_id").getAsString());
-            chapter.setWords(jsonObject.get("words").getAsString());
-            if (i + 1 <= freeChapterNum) {
-                chapter.setReadAble("0");
-            }
-            list.add(chapter);
-        }
-        redisUtil.setWithTime(key, list);
-        return list;
-    }
 
     @Override
     public List<SearchKeyword> getSearchKeywordBySex(String sex) {
-        String key = getKey("searchKeyword", sex);
-        Object o = redisUtil.get(key);
-        if (o != null) {
-            return (List<SearchKeyword>) o;
-        } else {
-            return getSearchKeywordsCache(key, sex);
-        }
+        return cacheService.getSearchKeywordsCache(sex);
     }
 
-    private List<SearchKeyword> getSearchKeywordsCache(String key, String sex) {
-        Object o = redisUtil.get(key);
-        if (o != null) {
-            return (List<SearchKeyword>) o;
-        }
-
-        SearchKeywordExample example = SearchKeywordExample.newAndCreateCriteria()
-                .andSexEqualTo(sex)
-                .example();
-        example.orderBy(SearchKeyword.Column.weigh.desc());
-        List<SearchKeyword> searchKeywords = searchKeywordMapper.selectByExample(example);
-
-        redisUtil.setWithTime(key, searchKeywords);
-        return searchKeywords;
-    }
 
     @Override
     public List<BookRes> topRecommend(QueryVO queryVO) {
-        List<BookRes> bookRes = bookMapper2.topRecommend(queryVO, 0, 20);
+        List<BookRes> bookRes = cacheService.setTopRecommendCache(queryVO.getSex());
         return getRandom(bookRes);
     }
 
-    private synchronized List<BookRes> setTopRecommendCache(String key, QueryVO queryVO) {
-        Object o = redisUtil.get(key);
-        if (o != null) {
-            return (List<BookRes>) o;
-        }
-        List<BookRes> bookRes = bookMapper2.topRecommend(queryVO, 0, 20);
-        redisUtil.setWithTime(key, bookRes);
-        return bookRes;
-    }
 
     @Override
     public List<BookRes> smartRecommand(QueryVO queryVO) {
         String key = getKey("smartRecommand", queryVO.getSex());
         Object o = redisUtil.get(key);
         if (o == null) {
-            List<BookRes> bookRes = setSmartRecommandCache(queryVO, key);
+            List<BookRes> bookRes = cacheService.setSmartRecommandCache(queryVO.getSex());
             return bookRes;
         } else {
             return (List<BookRes>) o;
         }
     }
 
-    private synchronized List<BookRes> setSmartRecommandCache(QueryVO queryVO, String key) {
-        Object o = redisUtil.get(key);
-        if (o != null) {
-            return (List<BookRes>) o;
-        }
-        List<BookRes> bookRes = bookMapper2.smartRecommand(queryVO);
-        redisUtil.setWithTime(key, bookRes);
-        return bookRes;
-    }
-
 
     @Autowired
     private ConfigMapper configMapper;
@@ -412,7 +263,7 @@ public class BookServiceImpl implements BookService {
     @Override
     public Result<BookContent> getContentByContentId(BookContentVO bookContentVO) {
         BookContent content = null;
-        Book book = getBookById(bookContentVO.getBookId());
+        Book book = cacheService.getBookById(bookContentVO.getBookId());
         //是否是付费章节
         Integer freeChapterNum = book.getFreeChapterNum();
         if (freeChapterNum == null) { //查看默认配置
@@ -477,7 +328,7 @@ public class BookServiceImpl implements BookService {
                     // 更新到 user
                     int i = userMapper.updateUserKandian(user, kandian, 0, DateUtils.getNow());
                     checkUpdate(i);
-                    updateUserByIdCache(user.getId());
+                    cacheService.updateUserByIdCache(user.getId());
 
                 } else {
                     return Result.failure(ResultCode.NOMONEY);
@@ -523,37 +374,9 @@ public class BookServiceImpl implements BookService {
     }
 
     private BookContent getBookContent(BookContentVO bookContentVO) {
-        String key = getKey("bookContent", bookContentVO.getBookId(), bookContentVO.getContentId());
-        Object o = redisUtil.get(key);
-        if (o != null) {
-            return (BookContent) o;
-        } else {
-            return setBookContentCache(key, bookContentVO);
-        }
+        return cacheService.setBookContentCache(bookContentVO.getBookId(), bookContentVO.getContentId(), bookContentVO.getContentName());
     }
 
-    private synchronized BookContent setBookContentCache(String key, BookContentVO bookContentVO) {
-        Object o = redisUtil.get(key);
-        if (o != null) {
-            return (BookContent) o;
-        }
-
-        BookContent bookContent;
-        // 修改过的章节
-        String content = getEditBookContentById(bookContentVO.getBookId(), bookContentVO.getContentId());
-        if (content != null) {
-            return getBookContentFromVO(bookContentVO, content);
-        }
-
-        if (bookContentVO.getBookId() > 110_0000 && bookContentVO.getBookId() < 110_9999) {
-            // 自定义的书籍
-            bookContent = getBookContentFromDB(bookContentVO);
-        } else {
-            bookContent = getBookContentFromRemote(bookContentVO);
-        }
-        redisUtil.setWithTime(key, bookContent);
-        return bookContent;
-    }
 
     private void checkUpdate(int i) {
         if (i <= 0) {
@@ -622,15 +445,16 @@ public class BookServiceImpl implements BookService {
         );
     }
 
+    public Book getBookById(Long id) {
+        return cacheService.getBookById(id);
+    }
+
     /**
      * 获取版权方章节内容
      *
-     * @param bookContentVO
      * @return
      */
-    private BookContent getBookContentFromRemote(BookContentVO bookContentVO) {
-        Long bookId = bookContentVO.getBookId();
-        Long contentId = bookContentVO.getContentId();
+    public BookContent getBookContentFromRemote(Long bookId, Long contentId) {
         String contentUrl = "http://new.emeixs.com/index.php/Home/Interface/content/bid/%s/cid/%s";
         if (bookId == null || contentId == null) {
             return null;
@@ -648,7 +472,7 @@ public class BookServiceImpl implements BookService {
             content.setChapterId(jsonObject.get("CONTENT_ID").getAsString());
             content.setIsPay(jsonObject.get("ispay").getAsString());
         } catch (Exception e) {
-            logger.info(e.getMessage());
+            log.error(e.getMessage());
             return null;
         }
         return content;
@@ -837,23 +661,23 @@ public class BookServiceImpl implements BookService {
         return true;
     }
 
-    private BookContent getBookContentFromDB(BookContentVO bookContentVO) {
+    public BookContent getBookContentFromDB(Long bookId, Long contentId, String contentName) {
         UploadBook uploadBook = uploadBookMapper.selectOneByExampleSelective(UploadBookExample.newAndCreateCriteria()
-                .andBookIdEqualTo(bookContentVO.getBookId())
-                .andChapterIdEqualTo(bookContentVO.getContentId())
+                .andBookIdEqualTo(bookId)
+                .andChapterIdEqualTo(contentId)
                 .example(), UploadBook.Column.content);
         if (uploadBook == null) {
             return null;
         } else {
-            return getBookContentFromVO(bookContentVO, uploadBook.getContent());
+            return getBookContentFromVO(bookId, contentId, contentName, uploadBook.getContent());
         }
     }
 
-    private BookContent getBookContentFromVO(BookContentVO bookContentVO, String content) {
+    public BookContent getBookContentFromVO(Long bookId, Long contenId, String contentName, String content) {
         BookContent bookContent = new BookContent();
-        bookContent.setBookId(bookContentVO.getBookId() + "");
-        bookContent.setChapterId(bookContentVO.getContentId() + "");
-        bookContent.setName(bookContentVO.getContentName());
+        bookContent.setBookId(bookId + "");
+        bookContent.setChapterId(contenId + "");
+        bookContent.setName(contentName);
         bookContent.setContent(content);
         return bookContent;
     }
@@ -868,99 +692,17 @@ public class BookServiceImpl implements BookService {
      * @return
      */
     public int getDefaultFreeChapterNum() {
-        String key = getKey("defaultFreeChapterNum");
-        Object o = redisUtil.get(key);
-        if (o == null) {
-            int book_free_chapter_num = setBook_free_chapter_num(key);
-            return book_free_chapter_num;
-        } else {
-            return (int) o;
-        }
-    }
-
-    private synchronized int setBook_free_chapter_num(String key) {
-        Object o = redisUtil.get(key);
-        if (o != null) {
-            return (int) o;
-        }
-        int book_free_chapter_num = Integer.parseInt(configMapper.selectByName("book_free_chapter_num").getValue());
-        redisUtil.setWithTime(key, book_free_chapter_num);
-        return book_free_chapter_num;
-    }
-
-    public Book getBookById(Long id) {
-        String key = getKey("book", id);
-        Object o = redisUtil.get(key);
-        if (o == null) {
-            return updateBookByIdToRedis(key, id);
-        } else {
-            return (Book) o;
-        }
-    }
-
-    public synchronized Book updateBookByIdToRedis(String key, Long id) {
-        Object o = redisUtil.get(key);
-        if (o != null) {
-            return (Book) o;
-        }
-        Book obj = bookMapper.selectByPrimaryKey(id);
-        redisUtil.setWithTime(key, obj);
-        return obj;
+        return cacheService.setBook_free_chapter_num();
     }
 
     public User getUserById(Long id) {
-        String key = getUserKey(id);
-        Object o = redisUtil.get(key);
-        if (o == null) {
-            return updateUserByIdCache(id);
-        } else {
-            return (User) o;
-        }
+        return cacheService.updateUserByIdCache(id);
     }
 
     private String getUserKey(Long id) {
         return getKey("user", id);
     }
 
-    public synchronized User updateUserByIdCache(Long id) {
-        String key = getUserKey(id);
-        Object o = redisUtil.get(key);
-        if (o != null) {
-            return (User) o;
-        }
-        User obj = userMapper.selectByPrimaryKey(id);
-        redisUtil.setWithTime(key, obj);
-        return obj;
-    }
-
-    public String getCategoryName(Integer id) {
-        String key = getKey("category");
-        Object o = redisUtil.hashGet(key, id);
-        if (o == null) {
-            String name = setCategoryCache(id, key);
-            return name;
-        } else {
-            return (String) o;
-        }
-    }
-
-    private synchronized String setCategoryCache(Integer id, String key) {
-        Object o = redisUtil.hashGet(key, id);
-        if (o != null) {
-            return (String) o;
-        }
-        List<BookCategory> bookCategories = bookCategoryMapper.selectByExample(BookCategoryExample.newAndCreateCriteria().example());
-        String name = "";
-        for (BookCategory x : bookCategories) {
-            redisUtil.hashSet(key, x.getId(), x.getName());
-            if (x.getId() == id) {
-                name = x.getName();
-            }
-        }
-        redisUtil.expire(key);
-        return name;
-    }
-
     public String getEditBookContentById(Long bookId, Long chapterId) {
         String key = getKey("edit_book", bookId, chapterId);
         Object o = redisUtil.get(key);

+ 22 - 0
book-server/src/test/java/com/book/server/cache/CacheServiceTest.java

@@ -0,0 +1,22 @@
+package com.book.server.cache;
+
+import com.book.dao.cps.pojo.User;
+import com.book.server.service.CacheService;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@SpringBootTest
+@RunWith(SpringRunner.class)
+public class CacheServiceTest {
+
+    @Autowired
+    private CacheService cacheService;
+    @Test
+    public void testTest1() {
+        User user = new User();
+        user.setId(123L);
+    }
+}