├── .gitignore ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── fengzhu │ │ └── reading │ │ ├── CommonResponse.java │ │ ├── Constants.java │ │ ├── ReadingApplication.java │ │ ├── config │ │ ├── AuthWebMvcConfigurer.java │ │ ├── ElasticSearchConfig.java │ │ ├── RabbitmqConfig.java │ │ ├── RedisConfig.java │ │ └── SpringDocConfig.java │ │ ├── consumer │ │ └── LikesMessageConsumer.java │ │ ├── controller │ │ ├── BookController.java │ │ ├── BookRatingController.java │ │ ├── BookReviewController.java │ │ ├── LikesController.java │ │ ├── TagController.java │ │ └── UserController.java │ │ ├── converter │ │ ├── BookAvgRatingConverter.java │ │ ├── BookConverter.java │ │ ├── BookRatingConverter.java │ │ ├── BookReviewConverter.java │ │ ├── LikesUserRecordConverter.java │ │ ├── TagConverter.java │ │ ├── TagGroupConverter.java │ │ └── UserConverter.java │ │ ├── dataObject │ │ ├── BaseEntity.java │ │ ├── Book.java │ │ ├── BookAvgRating.java │ │ ├── BookES.java │ │ ├── BookRating.java │ │ ├── BookReview.java │ │ ├── BookTag.java │ │ ├── LikesBusiness.java │ │ ├── LikesStatistic.java │ │ ├── LikesUserRecord.java │ │ ├── Tag.java │ │ ├── TagGroup.java │ │ └── User.java │ │ ├── dto │ │ ├── BookAvgRatingDTO.java │ │ ├── BookDTO.java │ │ ├── BookRankDTO.java │ │ ├── BookRatingDTO.java │ │ ├── BookReviewDTO.java │ │ ├── LikesUserRecordDTO.java │ │ ├── TagDTO.java │ │ ├── TagGroupDTO.java │ │ └── UserDTO.java │ │ ├── enums │ │ └── Enable.java │ │ ├── exceptions │ │ └── TokenAuthExpiredException.java │ │ ├── interceptors │ │ ├── AuthHandlerInterceptor.java │ │ └── GlobalExceptionHandler.java │ │ ├── repository │ │ ├── BookAvgRatingRepository.java │ │ ├── BookESRepository.java │ │ ├── BookRatingRepository.java │ │ ├── BookRepository.java │ │ ├── BookReviewRepository.java │ │ ├── BookTagRepository.java │ │ ├── LikesStatisticRepository.java │ │ ├── LikesUserRecordRepository.java │ │ ├── TagGroupRepository.java │ │ ├── TagRepository.java │ │ └── UserRepository.java │ │ ├── service │ │ ├── BookAvgRatingService.java │ │ ├── BookRatingService.java │ │ ├── BookReviewService.java │ │ ├── BookService.java │ │ ├── LikesService.java │ │ ├── RabbitmqService.java │ │ ├── TagService.java │ │ ├── UserService.java │ │ └── impl │ │ │ ├── BookAvgRatingServiceImpl.java │ │ │ ├── BookRatingServiceImpl.java │ │ │ ├── BookReviewServiceImpl.java │ │ │ ├── BookServiceImpl.java │ │ │ ├── LikesServiceImpl.java │ │ │ ├── TagServiceImpl.java │ │ │ └── UserServiceImpl.java │ │ ├── task │ │ └── BookAvgScoreTask.java │ │ ├── utils │ │ ├── BaseContext.java │ │ └── JwtUtils.java │ │ └── validator │ │ ├── BookRatingValidator.java │ │ ├── BookReviewValidator.java │ │ ├── BookValidator.java │ │ └── LikesValidator.java └── resources │ └── application.properties └── test └── java └── com └── fengzhu └── reading └── ReadingApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | 35 | .mvn/ 36 | mvnw 37 | mvnw.cmd 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 基于spring boot的一个学习项目,会使用到redis, rabbitmq, elastic search等框架 2 | 部署简单,非常适合学习提高 3 | 4 | 实现一个类似豆瓣读书 [https://book.douban.com/](https://book.douban.com/) 类似功能的网站,后端系统API应该如何设计 5 | 6 | ### 业务需求 7 | + 支持用户登陆注册 8 | + 展示图书列表,需要分页,支持按标签过滤 9 | + 图书标签,按组别分类,展示所有标签的时候需要展示每个标签包含的图书 10 | + 展示畅销图书排行榜 11 | + 用户可以对图书评分,评论 12 | + 图书详情页面需要展示 图书基础信息,评分信息,书评列表 13 | + 点赞系统支持对图书,书评的点赞以及查看用户的点赞列表 14 | + 支持图书的全文搜索 15 | 16 | 17 | 18 | ### 数据库设计 19 | ![](https://cdn.nlark.com/yuque/0/2024/png/26411187/1717507556167-297d05e4-d57e-405b-85db-5fa58891da03.png) 20 | 21 | 22 | 23 | ### API 24 | + 用户注册 25 | + 用户登陆 26 | + 新增图书 /book post 27 | + 更新图书 /book put 28 | + 查询图书列表,支持按标签过滤 /books get 29 | + 查询图书详情 30 | + 查询畅销图书排行榜 /book/rank get 31 | + 搜索图书(接入es) /book/search 32 | + 新增图书评分 /book/rating 33 | + 新增图书书评 /book/review 34 | + 查询图书书评列表 支持分页 35 | + 新增标签 /tag post 36 | + 查询所有图书标签,按标签组别分类 /tags get 37 | + 点赞接口,支持点赞图书,书评等 38 | + 查询用户的点赞列表 39 | + 查询图书或者书评的点赞总数 40 | 41 | 42 | 43 | ### 项目亮点 44 | #### 利用bitmap算法减少关联数据量,利用位运算提高效率 45 | #### 利用canal同步mysql数据到es, 使用es的全文搜索功能 46 | 安装es跟kibana: [https://www.cnblogs.com/benjieqiang/p/17501293.html](https://www.cnblogs.com/benjieqiang/p/17501293.html) 47 | 48 | 安装canal-server, canal-adapter: [https://www.macrozheng.com/project/canal_start.html](https://www.macrozheng.com/project/canal_start.html) 49 | 50 | #### 利用redis实现图书的热度排行榜 51 | #### spring boot定时任务同步数据 52 | #### 利用completableFuture提升图书详情接口性能 53 | #### 利用rabbitmq,redis实现支持高并发读写的点赞系统 54 | 55 | 56 | ### 启动依赖 57 | redis:docker安装 58 | 59 | rabbitmq: docker安装 60 | 61 | elastic search: docker安装 62 | 63 | 安装canal-server, canal-adapter: [https://www.macrozheng.com/project/canal_start.html](https://www.macrozheng.com/project/canal_start.html) 64 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 3.2.5 9 | 10 | 11 | com.fengzhu 12 | reading 13 | 0.0.1-SNAPSHOT 14 | reading 15 | a reading system simulating douban 16 | 17 | 17 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-data-jpa 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-web 27 | 28 | 29 | 30 | com.mysql 31 | mysql-connector-j 32 | runtime 33 | 34 | 35 | 36 | org.projectlombok 37 | lombok 38 | true 39 | 40 | 41 | 42 | org.springdoc 43 | springdoc-openapi-starter-webmvc-ui 44 | 2.3.0 45 | 46 | 47 | 48 | com.google.guava 49 | guava 50 | 32.1.3-jre 51 | 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-data-redis 56 | 57 | 58 | io.lettuce 59 | lettuce-core 60 | 61 | 62 | 63 | 64 | 65 | redis.clients 66 | jedis 67 | 68 | 69 | org.apache.commons 70 | commons-pool2 71 | 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-starter-amqp 76 | 77 | 78 | org.springframework.amqp 79 | spring-rabbit-test 80 | test 81 | 82 | 83 | 84 | org.springframework.data 85 | spring-data-elasticsearch 86 | 87 | 88 | 89 | org.elasticsearch.client 90 | elasticsearch-rest-high-level-client 91 | 7.16.1 92 | 93 | 94 | 95 | com.alibaba.otter 96 | canal.client 97 | 1.1.6 98 | 99 | 100 | 101 | com.auth0 102 | java-jwt 103 | 3.10.3 104 | 105 | 106 | 107 | 108 | com.alibaba.otter 109 | canal.protocol 110 | 1.1.6 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | org.springframework.boot 122 | spring-boot-starter-test 123 | test 124 | 125 | 126 | 127 | 128 | 129 | 130 | org.springframework.boot 131 | spring-boot-maven-plugin 132 | 133 | 134 | 135 | org.projectlombok 136 | lombok 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/CommonResponse.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class CommonResponse { 7 | 8 | private T data; 9 | private boolean success; 10 | private String errorMsg; 11 | 12 | public static CommonResponse newSuccess(K data) { 13 | CommonResponse response = new CommonResponse<>(); 14 | response.setData(data); 15 | response.setSuccess(true); 16 | return response; 17 | } 18 | 19 | public static CommonResponse newFail(String errorMsg, K data) { 20 | CommonResponse response = new CommonResponse<>(); 21 | response.setErrorMsg(errorMsg); 22 | response.setSuccess(false); 23 | response.setData(data); 24 | return response; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/Constants.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading; 2 | 3 | public class Constants { 4 | 5 | public static final String BOOK_RANK_KEY = "book-rank"; 6 | 7 | public static final String LIKE_USER_KEY = "likes-user-"; 8 | 9 | public static final String LIKE_STATISTIC_KEY = "likes-statistic-"; 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/ReadingApplication.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.scheduling.annotation.EnableScheduling; 6 | 7 | @SpringBootApplication 8 | @EnableScheduling 9 | public class ReadingApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(ReadingApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/config/AuthWebMvcConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.config; 2 | 3 | import com.fengzhu.reading.interceptors.AuthHandlerInterceptor; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 8 | 9 | @Configuration 10 | public class AuthWebMvcConfigurer implements WebMvcConfigurer { 11 | 12 | @Autowired 13 | private AuthHandlerInterceptor authHandlerInterceptor; 14 | 15 | @Override 16 | public void addInterceptors(InterceptorRegistry registry) { 17 | registry.addInterceptor(authHandlerInterceptor) 18 | .addPathPatterns("/**") 19 | .excludePathPatterns("/user/**", "/swagger-ui.html", 20 | "/swagger-ui/**", "/v3/api-docs/**"); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/config/ElasticSearchConfig.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.data.elasticsearch.client.ClientConfiguration; 5 | import org.springframework.data.elasticsearch.client.elc.ElasticsearchConfiguration; 6 | import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; 7 | 8 | @Configuration 9 | @EnableElasticsearchRepositories(basePackages = "com.fengzhu.reading.repository") 10 | public class ElasticSearchConfig extends ElasticsearchConfiguration { 11 | 12 | @Override 13 | public ClientConfiguration clientConfiguration() { 14 | return ClientConfiguration.builder() 15 | .connectedTo("localhost:9200").build(); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/config/RabbitmqConfig.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.config; 2 | 3 | import org.springframework.amqp.core.*; 4 | import org.springframework.amqp.rabbit.core.RabbitTemplate; 5 | import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; 6 | import org.springframework.amqp.support.converter.MessageConverter; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.amqp.rabbit.connection.ConnectionFactory; 11 | 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | 15 | @Configuration 16 | public class RabbitmqConfig { 17 | 18 | @Value("${rabbitmq.reading.queue}") 19 | private String queueName; 20 | 21 | @Value("${rabbitmq.reading.exchange}") 22 | private String exchange; 23 | 24 | @Value("${rabbitmq.reading.routingkey}") 25 | private String routingkey; 26 | 27 | @Value("${rabbitmq.reading.dlq.queue}") 28 | private String dlqQueueName; 29 | 30 | @Value("${rabbitmq.reading.dlq.exchange}") 31 | private String dlqExchange; 32 | 33 | @Value("${rabbitmq.reading.dlq.routingkey}") 34 | private String dlqRoutingkey; 35 | 36 | @Bean 37 | Queue queue() { 38 | Map params = new HashMap<>(); 39 | params.put("x-dead-letter-exchange", dlqExchange); 40 | params.put("x-dead-letter-routing-key", dlqRoutingkey); 41 | return QueueBuilder.durable(queueName).withArguments(params).build(); 42 | } 43 | 44 | @Bean 45 | DirectExchange exchange() { 46 | return new DirectExchange(exchange); 47 | } 48 | 49 | @Bean 50 | Binding binding(Queue queue, DirectExchange exchange) { 51 | return BindingBuilder.bind(queue).to(exchange).with(routingkey); 52 | } 53 | 54 | @Bean 55 | Queue dlqQueue() { 56 | return new Queue(dlqQueueName); 57 | } 58 | 59 | @Bean 60 | public DirectExchange dlqExchange(){ 61 | return new DirectExchange(dlqExchange); 62 | } 63 | 64 | @Bean 65 | public MessageConverter jsonMessageConverter() { 66 | return new Jackson2JsonMessageConverter(); 67 | } 68 | 69 | @Bean 70 | Binding dlqBinding(Queue dlqQueue, DirectExchange dlqExchange) { 71 | return BindingBuilder.bind(dlqQueue).to(dlqExchange).with(dlqRoutingkey); 72 | } 73 | 74 | @Bean 75 | public AmqpTemplate amqpTemplate(ConnectionFactory connectionFactory) { 76 | final RabbitTemplate template = new RabbitTemplate(connectionFactory); 77 | template.setMessageConverter(jsonMessageConverter()); 78 | return template; 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/config/RedisConfig.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.redis.connection.RedisConnectionFactory; 6 | import org.springframework.data.redis.core.RedisTemplate; 7 | import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; 8 | import org.springframework.data.redis.serializer.StringRedisSerializer; 9 | 10 | @Configuration 11 | public class RedisConfig { 12 | 13 | @Bean("redisTemplate") 14 | public RedisTemplate redisTemplate(RedisConnectionFactory factory) { 15 | RedisTemplate redisTemplate = new RedisTemplate<>(); 16 | redisTemplate.setConnectionFactory(factory); 17 | redisTemplate.setKeySerializer(new StringRedisSerializer()); 18 | redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); 19 | return redisTemplate; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/config/SpringDocConfig.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.config; 2 | 3 | import io.swagger.v3.oas.models.ExternalDocumentation; 4 | import io.swagger.v3.oas.models.OpenAPI; 5 | import io.swagger.v3.oas.models.info.Info; 6 | import io.swagger.v3.oas.models.info.License; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | 11 | @Configuration 12 | public class SpringDocConfig { 13 | 14 | @Bean 15 | public OpenAPI api() { 16 | return new OpenAPI() 17 | .info(new Info().title("reading system api") 18 | .description("restful api") 19 | .version("v1.0.0") 20 | .license(new License().name("").url(""))) 21 | .externalDocs(new ExternalDocumentation().description("") 22 | .url("")); 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/consumer/LikesMessageConsumer.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.consumer; 2 | 3 | 4 | import com.fengzhu.reading.converter.LikesUserRecordConverter; 5 | import com.fengzhu.reading.dataObject.LikesStatistic; 6 | import com.fengzhu.reading.dataObject.LikesUserRecord; 7 | import com.fengzhu.reading.dto.LikesUserRecordDTO; 8 | import com.fengzhu.reading.repository.LikesStatisticRepository; 9 | import com.fengzhu.reading.repository.LikesUserRecordRepository; 10 | import com.fengzhu.reading.validator.LikesValidator; 11 | import com.google.gson.Gson; 12 | import lombok.Data; 13 | import lombok.extern.slf4j.Slf4j; 14 | import org.springframework.amqp.rabbit.annotation.RabbitListener; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.beans.factory.annotation.Value; 17 | import org.springframework.data.redis.core.RedisTemplate; 18 | import org.springframework.stereotype.Component; 19 | 20 | import static com.fengzhu.reading.Constants.LIKE_STATISTIC_KEY; 21 | import static com.fengzhu.reading.Constants.LIKE_USER_KEY; 22 | 23 | @Component 24 | @Slf4j 25 | @Data 26 | public class LikesMessageConsumer { 27 | 28 | @Value("${rabbitmq.reading.queue}") 29 | private String queueName; 30 | 31 | @Value("${rabbitmq.reading.exchange}") 32 | private String exchange; 33 | 34 | @Autowired 35 | private LikesUserRecordRepository likesUserRecordRepository; 36 | 37 | @Autowired 38 | private LikesStatisticRepository likesStatisticRepository; 39 | 40 | @Autowired 41 | private RedisTemplate redisTemplate; 42 | 43 | @Autowired 44 | private LikesValidator likesValidator; 45 | 46 | private Gson gson = new Gson(); 47 | 48 | @RabbitListener(queues = "${rabbitmq.reading.queue}") 49 | public void handleMessage(LikesUserRecordDTO likesUserRecordDTO) { 50 | log.info("Received message from queue {}: message:{}", queueName, gson.toJson(likesUserRecordDTO)); 51 | likesValidator.validateAddNewBook(likesUserRecordDTO); 52 | likesUserRecordRepository.findUserLikeRecord(likesUserRecordDTO.getUserId(), likesUserRecordDTO.getBusinessId(), 53 | likesUserRecordDTO.getItemId()) 54 | .ifPresentOrElse(likesUserRecord -> doUnLikeAction(likesUserRecord), () -> doLikeAction(likesUserRecordDTO)); 55 | } 56 | 57 | private void doLikeAction(LikesUserRecordDTO likesUserRecordDTO) { 58 | LikesUserRecord likesUserRecord = LikesUserRecordConverter.convertToLikesUserRecord(likesUserRecordDTO); 59 | likesUserRecordRepository.save(likesUserRecord); 60 | 61 | String likesStatisticKey = LIKE_STATISTIC_KEY + likesUserRecordDTO.getBusinessId() + ":" + likesUserRecordDTO.getItemId(); 62 | 63 | likesStatisticRepository.findByBusinessIdAndItemId(likesUserRecordDTO.getBusinessId(), 64 | likesUserRecordDTO.getItemId()) 65 | .ifPresentOrElse(likesStatistic -> { 66 | long newLikeCount = likesStatistic.getLikeCount() + 1; 67 | likesStatistic.setLikeCount(newLikeCount); 68 | likesStatisticRepository.save(likesStatistic); 69 | redisTemplate.opsForValue().set(likesStatisticKey, newLikeCount); 70 | }, () -> { 71 | LikesStatistic likesStatistic = LikesStatistic.builder() 72 | .businessId(likesUserRecordDTO.getBusinessId()) 73 | .itemId(likesUserRecordDTO.getItemId()) 74 | .likeCount(1).build(); 75 | 76 | likesStatisticRepository.save(likesStatistic); 77 | redisTemplate.opsForValue().set(likesStatisticKey, 1L); 78 | }); 79 | 80 | redisTemplate.opsForSet().add(LIKE_USER_KEY + likesUserRecordDTO.getUserId(), likesUserRecordDTO.getBusinessId() + ":" + 81 | likesUserRecordDTO.getItemId()); 82 | 83 | } 84 | 85 | private void doUnLikeAction(LikesUserRecord likesUserRecord) { 86 | likesUserRecord.setLikes(false); 87 | likesUserRecordRepository.save(likesUserRecord); 88 | 89 | String likesStatisticKey = LIKE_STATISTIC_KEY + likesUserRecord.getBusinessId() + ":" + likesUserRecord.getItemId(); 90 | likesStatisticRepository.findByBusinessIdAndItemId(likesUserRecord.getBusinessId(), 91 | likesUserRecord.getItemId()) 92 | .ifPresentOrElse(likesStatistic -> { 93 | long newLikeCount = likesStatistic.getLikeCount() - 1; 94 | likesStatistic.setLikeCount(newLikeCount); 95 | likesStatisticRepository.save(likesStatistic); 96 | 97 | redisTemplate.opsForValue().set(likesStatisticKey, newLikeCount); 98 | }, () -> { 99 | log.info("there is no likes statistic for businessId:{}, itemId:{}", 100 | likesUserRecord.getBusinessId(), likesUserRecord.getItemId()); 101 | }); 102 | 103 | redisTemplate.opsForSet().remove(LIKE_USER_KEY + likesUserRecord.getUserId(), likesUserRecord.getBusinessId() + ":" + 104 | likesUserRecord.getItemId()); 105 | 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/controller/BookController.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.controller; 2 | 3 | import com.fengzhu.reading.CommonResponse; 4 | import com.fengzhu.reading.dto.BookAvgRatingDTO; 5 | import com.fengzhu.reading.dto.BookDTO; 6 | import com.fengzhu.reading.dto.BookRankDTO; 7 | import com.fengzhu.reading.dto.BookReviewDTO; 8 | import com.fengzhu.reading.service.BookAvgRatingService; 9 | import com.fengzhu.reading.service.BookReviewService; 10 | import com.fengzhu.reading.service.BookService; 11 | import com.fengzhu.reading.validator.BookValidator; 12 | import lombok.extern.slf4j.Slf4j; 13 | import org.apache.commons.lang.StringUtils; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.data.domain.Page; 16 | import org.springframework.data.domain.PageRequest; 17 | import org.springframework.data.domain.Sort; 18 | import org.springframework.web.bind.annotation.*; 19 | 20 | import java.util.List; 21 | import java.util.concurrent.CompletableFuture; 22 | 23 | @RestController 24 | @Slf4j 25 | public class BookController { 26 | 27 | @Autowired 28 | private BookService bookService; 29 | 30 | @Autowired 31 | private BookReviewService bookReviewService; 32 | 33 | @Autowired 34 | private BookAvgRatingService bookAvgRatingService; 35 | 36 | @Autowired 37 | private BookValidator bookValidator; 38 | 39 | @PostMapping("/book") 40 | public CommonResponse addNewBook(@RequestBody BookDTO bookDTO) { 41 | bookValidator.validateAddNewBook(bookDTO); 42 | return CommonResponse.newSuccess(bookService.addNewBook(bookDTO)); 43 | } 44 | 45 | @PutMapping("/book") 46 | public CommonResponse updateBook(@RequestBody BookDTO bookDTO) { 47 | return CommonResponse.newSuccess(bookService.updateBook(bookDTO)); 48 | } 49 | 50 | @GetMapping("/book") 51 | public CommonResponse> lookupBooks(@RequestParam(required = false) Long tagId, 52 | @RequestParam(required = false, defaultValue = "10") Integer pageSize, 53 | @RequestParam(required = false, defaultValue = "0") Integer pageNumber) { 54 | 55 | PageRequest pageRequest = PageRequest.of(pageNumber, pageSize); 56 | return CommonResponse.newSuccess(bookService.lookupBooks(pageRequest, tagId)); 57 | } 58 | 59 | @GetMapping("/book/{bookId}") 60 | public CommonResponse getBookById(@PathVariable Long bookId) { 61 | CompletableFuture bookFuture = CompletableFuture. 62 | supplyAsync(() -> bookService.getBookDTOById(bookId)); 63 | 64 | CompletableFuture> bookReviewFuture = CompletableFuture. 65 | supplyAsync(() -> bookReviewService.getBookReviewDTOListByBookId(bookId, PageRequest.of(0, 10, Sort.by("likeCount").descending()))); 66 | 67 | CompletableFuture bookAvgRatingFuture = CompletableFuture 68 | .supplyAsync(() -> bookAvgRatingService.getAvgRatingByBookId(bookId)); 69 | 70 | // 利用CompletableFuture实现异步加载book, rating, review 71 | CompletableFuture allTask = CompletableFuture.allOf(bookFuture, bookReviewFuture, bookAvgRatingFuture); 72 | CompletableFuture combinedFuture = allTask.thenApply(v -> { 73 | BookDTO bookDTO = bookFuture.join(); 74 | Page bookReviewDTOList = bookReviewFuture.join(); 75 | BookAvgRatingDTO bookAvgRatingDTO = bookAvgRatingFuture.join(); 76 | bookDTO.setBookReviewDTOList(bookReviewDTOList); 77 | bookDTO.setBookAvgRatingDTO(bookAvgRatingDTO); 78 | return bookDTO; 79 | }).whenComplete((res, ex) -> { 80 | if (ex != null) { 81 | log.error("getBookById occur exception", ex); 82 | } 83 | }); 84 | try { 85 | return CommonResponse.newSuccess(combinedFuture.get()); 86 | } catch (Throwable e) { 87 | return CommonResponse.newFail("获取book信息失败", null); 88 | } 89 | 90 | } 91 | 92 | @GetMapping("/book/rank") 93 | public CommonResponse> getBookRank(@RequestParam(required = false, defaultValue = "10") int size) { 94 | return CommonResponse.newSuccess(bookService.getBookRank(size)); 95 | } 96 | 97 | @GetMapping("/book/search") 98 | public CommonResponse> searchBooks(@RequestParam String keyword) { 99 | if (StringUtils.isEmpty(keyword)) { 100 | return CommonResponse.newSuccess(null); 101 | } 102 | return CommonResponse.newSuccess(bookService.searchBooks(keyword)); 103 | } 104 | 105 | 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/controller/BookRatingController.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.controller; 2 | 3 | import com.fengzhu.reading.CommonResponse; 4 | import com.fengzhu.reading.dto.BookRatingDTO; 5 | import com.fengzhu.reading.service.BookRatingService; 6 | import com.fengzhu.reading.validator.BookRatingValidator; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | @RestController 11 | public class BookRatingController { 12 | 13 | @Autowired 14 | private BookRatingValidator bookRatingValidator; 15 | 16 | @Autowired 17 | private BookRatingService bookRatingService; 18 | 19 | @PostMapping("/book/rating") 20 | public CommonResponse addNewBookRating(@RequestBody BookRatingDTO bookRatingDTO) { 21 | bookRatingValidator.validateAddNewBookRating(bookRatingDTO); 22 | return CommonResponse.newSuccess(bookRatingService.addNewBookRating(bookRatingDTO)); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/controller/BookReviewController.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.controller; 2 | 3 | import com.fengzhu.reading.CommonResponse; 4 | import com.fengzhu.reading.dto.BookReviewDTO; 5 | import com.fengzhu.reading.service.BookReviewService; 6 | import com.fengzhu.reading.validator.BookReviewValidator; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.data.domain.Page; 9 | import org.springframework.data.domain.PageRequest; 10 | import org.springframework.data.domain.Sort; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | @RestController 14 | public class BookReviewController { 15 | 16 | @Autowired 17 | private BookReviewService bookReviewService; 18 | 19 | @Autowired 20 | private BookReviewValidator bookReviewValidator; 21 | 22 | @PostMapping("/book/review") 23 | public CommonResponse addNewBookReview(@RequestBody BookReviewDTO bookReviewDTO) { 24 | bookReviewValidator.validateAddNewBookReview(bookReviewDTO); 25 | return CommonResponse.newSuccess(bookReviewService.addNewBookReview(bookReviewDTO)); 26 | } 27 | 28 | @GetMapping("/book/review/{bookId}") 29 | public CommonResponse> getBookReviewByBookId(@PathVariable long bookId, @RequestParam(value = "pageNumber", required = false, defaultValue = "0") int pageNumber, 30 | @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize, 31 | @RequestParam(required = false, defaultValue = "likeCount") String sortField) { 32 | 33 | return CommonResponse.newSuccess(bookReviewService.getBookReviewDTOListByBookId(bookId, 34 | PageRequest.of(pageNumber, pageSize, Sort.by(sortField).descending()))); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/controller/LikesController.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.controller; 2 | 3 | import com.fengzhu.reading.CommonResponse; 4 | import com.fengzhu.reading.dto.LikesUserRecordDTO; 5 | import com.fengzhu.reading.service.LikesService; 6 | import com.fengzhu.reading.utils.BaseContext; 7 | import com.fengzhu.reading.validator.LikesValidator; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import java.util.List; 12 | 13 | @RestController 14 | public class LikesController { 15 | 16 | @Autowired 17 | private LikesService likesService; 18 | 19 | @Autowired 20 | private LikesValidator likesValidator; 21 | 22 | @PostMapping("/likes") 23 | public CommonResponse addlikeItem(@RequestBody LikesUserRecordDTO likesUserRecordDTO) { 24 | likesValidator.validateAddNewBook(likesUserRecordDTO); 25 | return CommonResponse.newSuccess(likesService.addNewLikesRecord(likesUserRecordDTO)); 26 | } 27 | 28 | @GetMapping("/likes/{businessId}") 29 | public CommonResponse> getMyLikes(@PathVariable Long businessId) { 30 | long userId = BaseContext.getCurrentId(); 31 | return CommonResponse.newSuccess(likesService.getMyLikes(userId, businessId)); 32 | } 33 | 34 | @GetMapping("/likes/{businessId}/{itemId}") 35 | public CommonResponse getItemLikesCount(@PathVariable Long businessId, @PathVariable Long itemId) { 36 | return CommonResponse.newSuccess(likesService.getItemLikesCount(businessId, itemId)); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/controller/TagController.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.controller; 2 | 3 | 4 | import com.fengzhu.reading.CommonResponse; 5 | import com.fengzhu.reading.dto.TagDTO; 6 | import com.fengzhu.reading.dto.TagGroupDTO; 7 | import com.fengzhu.reading.service.TagService; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestBody; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import java.util.List; 15 | import java.util.Map; 16 | 17 | @RestController 18 | public class TagController { 19 | 20 | @Autowired 21 | private TagService tagService; 22 | 23 | @PostMapping("/tag") 24 | public CommonResponse addNewTag(@RequestBody TagDTO tagDTO) { 25 | return CommonResponse.newSuccess(tagService.addNewTag(tagDTO)); 26 | } 27 | 28 | @GetMapping("/tag") 29 | public CommonResponse>> getAllTags() { 30 | return CommonResponse.newSuccess(tagService.getAllTags()); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.controller; 2 | 3 | 4 | import com.fengzhu.reading.CommonResponse; 5 | import com.fengzhu.reading.dto.UserDTO; 6 | import com.fengzhu.reading.service.UserService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | @RestController 11 | public class UserController { 12 | 13 | @Autowired 14 | private UserService userService; 15 | 16 | @PostMapping("/user") 17 | public CommonResponse registryUser(@RequestBody UserDTO userDTO) { 18 | return CommonResponse.newSuccess(userService.registerUser(userDTO)); 19 | } 20 | 21 | @PostMapping("/user/login") 22 | public CommonResponse login(@RequestParam String userName, @RequestParam String password) { 23 | return CommonResponse.newSuccess(userService.login(userName, password)); 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/converter/BookAvgRatingConverter.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.converter; 2 | 3 | import com.fengzhu.reading.dataObject.BookAvgRating; 4 | import com.fengzhu.reading.dto.BookAvgRatingDTO; 5 | 6 | public class BookAvgRatingConverter { 7 | 8 | public static BookAvgRatingDTO convertToBookAvgRatingDTO(BookAvgRating bookAvgRating) { 9 | if (bookAvgRating == null) { 10 | return null; 11 | } 12 | 13 | return BookAvgRatingDTO.builder() 14 | .id(bookAvgRating.getId()) 15 | .bookId(bookAvgRating.getBookId()) 16 | .avgRatingScore(bookAvgRating.getAvgRatingScore()).build(); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/converter/BookConverter.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.converter; 2 | 3 | import com.fengzhu.reading.dataObject.Book; 4 | import com.fengzhu.reading.dataObject.BookES; 5 | import com.fengzhu.reading.dto.BookDTO; 6 | 7 | public class BookConverter { 8 | 9 | public static Book convertToBook(BookDTO bookDTO) { 10 | if (bookDTO == null) { 11 | return null; 12 | } 13 | return Book.builder() 14 | .id(bookDTO.getId()) 15 | .bookName(bookDTO.getBookName()) 16 | .author(bookDTO.getAuthor()) 17 | .introduction(bookDTO.getIntroduction()) 18 | .isbn(bookDTO.getIsbn()) 19 | .publishDate(bookDTO.getPublishDate()) 20 | .build(); 21 | 22 | } 23 | 24 | public static BookDTO converToBookDTO(Book book) { 25 | if (book == null) { 26 | return null; 27 | } 28 | return BookDTO.builder() 29 | .id(book.getId()) 30 | .bookName(book.getBookName()) 31 | .author(book.getAuthor()) 32 | .introduction(book.getIntroduction()) 33 | .isbn(book.getIsbn()) 34 | .publishDate(book.getPublishDate()).build(); 35 | } 36 | 37 | public static BookDTO converToBookDTO(BookES book) { 38 | if (book == null) { 39 | return null; 40 | } 41 | return BookDTO.builder() 42 | .id(book.getId()) 43 | .bookName(book.getBookName()) 44 | .author(book.getAuthor()) 45 | .introduction(book.getIntroduction()) 46 | .isbn(book.getIsbn()) 47 | .publishDate(book.getPublishDate()).build(); 48 | } 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/converter/BookRatingConverter.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.converter; 2 | 3 | import com.fengzhu.reading.dataObject.BookRating; 4 | import com.fengzhu.reading.dto.BookRatingDTO; 5 | 6 | public class BookRatingConverter { 7 | 8 | public static BookRating converToBookRating(BookRatingDTO bookRatingDTO) { 9 | if (bookRatingDTO == null) { 10 | return null; 11 | } 12 | 13 | return BookRating.builder() 14 | .id(bookRatingDTO.getId()) 15 | .bookId(bookRatingDTO.getBookId()) 16 | .userId(bookRatingDTO.getUserId()) 17 | .score(bookRatingDTO.getScore()) 18 | .rateDate(bookRatingDTO.getRateDate()).build(); 19 | } 20 | 21 | public static BookRatingDTO convertToBookRatingDTO(BookRating bookRating) { 22 | if (bookRating == null) { 23 | return null; 24 | } 25 | 26 | return BookRatingDTO.builder() 27 | .id(bookRating.getId()) 28 | .bookId(bookRating.getBookId()) 29 | .userId(bookRating.getUserId()) 30 | .score(bookRating.getScore()) 31 | .rateDate(bookRating.getRateDate()).build(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/converter/BookReviewConverter.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.converter; 2 | 3 | import com.fengzhu.reading.dataObject.BookReview; 4 | import com.fengzhu.reading.dto.BookReviewDTO; 5 | 6 | public class BookReviewConverter { 7 | 8 | public static BookReview convertToBookReview(BookReviewDTO bookReviewDTO) { 9 | if (bookReviewDTO == null) { 10 | return null; 11 | } 12 | return BookReview.builder() 13 | .id(bookReviewDTO.getId()) 14 | .bookId(bookReviewDTO.getBookId()) 15 | .reviewContent(bookReviewDTO.getReviewContent()) 16 | .userId(bookReviewDTO.getUserId()) 17 | .likeCount(bookReviewDTO.getLikeCount()) 18 | .dislikeCount(bookReviewDTO.getDislikeCount()) 19 | .build(); 20 | } 21 | 22 | public static BookReviewDTO convertToBookReviewDTO(BookReview bookReview) { 23 | if (bookReview == null) { 24 | return null; 25 | } 26 | 27 | return BookReviewDTO.builder() 28 | .id(bookReview.getId()) 29 | .bookId(bookReview.getBookId()) 30 | .reviewContent(bookReview.getReviewContent()) 31 | .likeCount(bookReview.getLikeCount()) 32 | .dislikeCount(bookReview.getDislikeCount()) 33 | .createTime(bookReview.getCreateTime()) 34 | .updateTime(bookReview.getUpdateTime()) 35 | .build(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/converter/LikesUserRecordConverter.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.converter; 2 | 3 | import com.fengzhu.reading.dataObject.LikesUserRecord; 4 | import com.fengzhu.reading.dto.LikesUserRecordDTO; 5 | 6 | public class LikesUserRecordConverter { 7 | 8 | public static LikesUserRecord convertToLikesUserRecord(LikesUserRecordDTO likesUserRecordDTO) { 9 | if (likesUserRecordDTO == null) { 10 | return null; 11 | } 12 | 13 | return LikesUserRecord.builder() 14 | .id(likesUserRecordDTO.getId()) 15 | .businessId(likesUserRecordDTO.getBusinessId()) 16 | .itemId(likesUserRecordDTO.getItemId()) 17 | .likes(likesUserRecordDTO.isLikes()) 18 | .userId(likesUserRecordDTO.getUserId()) 19 | .build(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/converter/TagConverter.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.converter; 2 | 3 | import com.fengzhu.reading.dataObject.Tag; 4 | import com.fengzhu.reading.dto.TagDTO; 5 | 6 | public class TagConverter { 7 | 8 | public static Tag convertToTag(TagDTO tagDTO) { 9 | return Tag.builder() 10 | .tagGroupId(tagDTO.getTagGroupId()) 11 | .tagName(tagDTO.getTagName()).build(); 12 | } 13 | 14 | public static TagDTO convertToTagDTO(Tag tag) { 15 | return TagDTO.builder() 16 | .id(tag.getId()) 17 | .tagValue(tag.getTagValue()) 18 | .tagName(tag.getTagName()) 19 | .tagGroupId(tag.getTagGroupId()) 20 | .build(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/converter/TagGroupConverter.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.converter; 2 | 3 | import com.fengzhu.reading.dataObject.TagGroup; 4 | import com.fengzhu.reading.dto.TagGroupDTO; 5 | 6 | public class TagGroupConverter { 7 | 8 | public static TagGroupDTO converToTagGroupDTO(TagGroup tagGroup) { 9 | if (tagGroup == null) { 10 | return null; 11 | } 12 | 13 | return TagGroupDTO.builder() 14 | .tagGroupId(tagGroup.getId()) 15 | .tagGroupName(tagGroup.getTagGroupName()).build(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/converter/UserConverter.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.converter; 2 | 3 | import com.fengzhu.reading.dataObject.User; 4 | import com.fengzhu.reading.dto.UserDTO; 5 | 6 | public class UserConverter { 7 | 8 | public static User converToUser(UserDTO userDTO) { 9 | if (userDTO == null) { 10 | return null; 11 | } 12 | return User.builder() 13 | .id(userDTO.getId()) 14 | .username(userDTO.getUsername()) 15 | .email(userDTO.getEmail()) 16 | .salt(userDTO.getSalt()) 17 | .build(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dataObject/BaseEntity.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dataObject; 2 | 3 | import jakarta.persistence.MappedSuperclass; 4 | import jakarta.persistence.PrePersist; 5 | import jakarta.persistence.PreUpdate; 6 | import lombok.Data; 7 | 8 | import java.time.Instant; 9 | 10 | @Data 11 | @MappedSuperclass 12 | public class BaseEntity { 13 | 14 | private long createTime; 15 | 16 | private long updateTime; 17 | 18 | @PrePersist 19 | public void onCreate() { 20 | if (this.createTime == 0L) { 21 | this.createTime = Instant.now().toEpochMilli(); 22 | this.updateTime = Instant.now().toEpochMilli(); 23 | } 24 | } 25 | 26 | @PreUpdate 27 | public void onUpdate() { 28 | this.updateTime = Instant.now().toEpochMilli(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dataObject/Book.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dataObject; 2 | 3 | import jakarta.persistence.Entity; 4 | import jakarta.persistence.GeneratedValue; 5 | import jakarta.persistence.Id; 6 | import jakarta.persistence.Table; 7 | import lombok.AllArgsConstructor; 8 | import lombok.Builder; 9 | import lombok.Data; 10 | 11 | import static jakarta.persistence.GenerationType.IDENTITY; 12 | 13 | @Entity 14 | @Table(name = "book") 15 | @Data 16 | @Builder 17 | @AllArgsConstructor 18 | public class Book extends BaseEntity { 19 | 20 | @Id 21 | @GeneratedValue(strategy = IDENTITY) 22 | private long id; 23 | 24 | private String bookName; 25 | 26 | private String author; 27 | 28 | private long publishDate; 29 | 30 | private String isbn; 31 | 32 | private String introduction; 33 | 34 | public Book() { 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dataObject/BookAvgRating.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dataObject; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Entity 10 | @Table(name = "book_avg_rating") 11 | @Data 12 | @Builder 13 | @AllArgsConstructor 14 | @NoArgsConstructor 15 | public class BookAvgRating extends BaseEntity { 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private long id; 20 | 21 | private long bookId; 22 | 23 | private float avgRatingScore; 24 | 25 | @Column(name = "enable") 26 | private boolean enable; 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dataObject/BookES.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dataObject; 2 | 3 | import lombok.Data; 4 | import org.springframework.data.annotation.Id; 5 | import org.springframework.data.elasticsearch.annotations.Document; 6 | import org.springframework.data.elasticsearch.annotations.Field; 7 | import org.springframework.data.elasticsearch.annotations.FieldType; 8 | 9 | @Document(indexName = "canal_book") 10 | @Data 11 | public class BookES { 12 | 13 | @Id 14 | private long id; 15 | 16 | @Field(name = "book_name", type = FieldType.Text, analyzer = "ik_smart", searchAnalyzer = "ik_smart") 17 | private String bookName; 18 | 19 | @Field(type = FieldType.Text, analyzer = "ik_smart", searchAnalyzer = "ik_smart") 20 | private String author; 21 | 22 | @Field(name = "publish_date") 23 | private long publishDate; 24 | 25 | @Field 26 | private String isbn; 27 | 28 | @Field(type = FieldType.Text, analyzer = "ik_smart", searchAnalyzer = "ik_smart") 29 | private String introduction; 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dataObject/BookRating.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dataObject; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Entity 10 | @Table(name = "book_rating") 11 | @Data 12 | @Builder 13 | @AllArgsConstructor 14 | @NoArgsConstructor 15 | public class BookRating extends BaseEntity{ 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private long id; 20 | 21 | private long bookId; 22 | 23 | private long userId; 24 | 25 | private int score; 26 | 27 | private long rateDate; 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dataObject/BookReview.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dataObject; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Entity 10 | @Table(name = "book_review") 11 | @Data 12 | @Builder 13 | @AllArgsConstructor 14 | @NoArgsConstructor 15 | public class BookReview extends BaseEntity { 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private long id; 20 | 21 | private long bookId; 22 | 23 | private long userId; 24 | 25 | private String reviewContent; 26 | 27 | private long likeCount; 28 | 29 | private long dislikeCount; 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dataObject/BookTag.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dataObject; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | 8 | @Entity 9 | @Table(name = "book_tag") 10 | @Builder 11 | @Data 12 | @AllArgsConstructor 13 | public class BookTag extends BaseEntity { 14 | 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private long id; 18 | 19 | private long bookId; 20 | 21 | private long tagGroupId; 22 | 23 | private long tagValue; 24 | 25 | public BookTag() { 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dataObject/LikesBusiness.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dataObject; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Entity 10 | @Table(name = "likes_business") 11 | @Data 12 | @Builder 13 | @AllArgsConstructor 14 | @NoArgsConstructor 15 | public class LikesBusiness extends BaseEntity { 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private long id; 20 | 21 | private String businessName; 22 | 23 | private String description; 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dataObject/LikesStatistic.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dataObject; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Entity 10 | @Table(name = "likes_statistic") 11 | @Data 12 | @AllArgsConstructor 13 | @NoArgsConstructor 14 | @Builder 15 | public class LikesStatistic extends BaseEntity { 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private long id; 20 | 21 | private long businessId; 22 | 23 | private long itemId; 24 | 25 | private long likeCount; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dataObject/LikesUserRecord.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dataObject; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Entity 10 | @Table(name = "likes_user_record") 11 | @Data 12 | @Builder 13 | @AllArgsConstructor 14 | @NoArgsConstructor 15 | public class LikesUserRecord extends BaseEntity { 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private long id; 20 | 21 | private long userId; 22 | 23 | private long businessId; 24 | 25 | private long itemId; 26 | 27 | private boolean likes; 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dataObject/Tag.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dataObject; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | 8 | @Entity 9 | @Table(name = "tag") 10 | @Builder 11 | @AllArgsConstructor 12 | @Data 13 | public class Tag extends BaseEntity { 14 | 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private long id; 18 | 19 | private String tagName; 20 | 21 | private long tagGroupId; 22 | 23 | private long tagValue; 24 | 25 | public Tag() { 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dataObject/TagGroup.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dataObject; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | @Entity 9 | @Table(name = "tag_group") 10 | @Data 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | public class TagGroup extends BaseEntity { 14 | 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private long id; 18 | 19 | private String tagGroupName; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dataObject/User.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dataObject; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Entity 10 | @Table 11 | @Data 12 | @Builder 13 | @NoArgsConstructor 14 | @AllArgsConstructor 15 | public class User extends BaseEntity { 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private long id; 20 | 21 | private String username; 22 | 23 | private String password; 24 | 25 | private String salt; 26 | 27 | private String email; 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dto/BookAvgRatingDTO.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dto; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Data 7 | @Builder 8 | public class BookAvgRatingDTO { 9 | 10 | private long id; 11 | 12 | private long bookId; 13 | 14 | private float avgRatingScore; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dto/BookDTO.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dto; 2 | 3 | import com.fengzhu.reading.dataObject.BookAvgRating; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import org.springframework.data.domain.Page; 7 | 8 | import java.util.List; 9 | 10 | @Data 11 | @Builder 12 | public class BookDTO { 13 | 14 | private long id; 15 | 16 | private String bookName; 17 | 18 | private String author; 19 | 20 | private long publishDate; 21 | 22 | private String isbn; 23 | 24 | private String introduction; 25 | 26 | private List tagDTOList; 27 | 28 | private Page bookReviewDTOList; 29 | 30 | private BookAvgRatingDTO bookAvgRatingDTO; 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dto/BookRankDTO.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dto; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Data 7 | @Builder 8 | public class BookRankDTO { 9 | 10 | private long bookId; 11 | 12 | private String bookName; 13 | 14 | private long hit; 15 | 16 | private int order; 17 | 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dto/BookRatingDTO.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dto; 2 | 3 | import com.fengzhu.reading.dataObject.BaseEntity; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | 7 | @Data 8 | @Builder 9 | public class BookRatingDTO extends BaseEntity { 10 | 11 | private long id; 12 | 13 | private long bookId; 14 | 15 | private long userId; 16 | 17 | private int score; 18 | 19 | private long rateDate; 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dto/BookReviewDTO.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dto; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Data 7 | @Builder 8 | public class BookReviewDTO { 9 | 10 | private long id; 11 | 12 | private long bookId; 13 | 14 | private long userId; 15 | 16 | private String reviewContent; 17 | 18 | private long likeCount; 19 | 20 | private long dislikeCount; 21 | 22 | private long createTime; 23 | 24 | private long updateTime; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dto/LikesUserRecordDTO.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dto; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Data 7 | @Builder 8 | public class LikesUserRecordDTO { 9 | 10 | private long id; 11 | 12 | private long userId; 13 | 14 | private long businessId; 15 | 16 | private long itemId; 17 | 18 | private boolean likes; 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dto/TagDTO.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dto; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Data 7 | @Builder 8 | public class TagDTO { 9 | 10 | private long id; 11 | 12 | private String tagName; 13 | 14 | private long tagGroupId; 15 | 16 | private long tagValue; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dto/TagGroupDTO.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dto; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Data 7 | @Builder 8 | public class TagGroupDTO { 9 | 10 | private long tagGroupId; 11 | 12 | private String tagGroupName; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/dto/UserDTO.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.dto; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import java.util.UUID; 9 | 10 | @Data 11 | @AllArgsConstructor 12 | @NoArgsConstructor 13 | public class UserDTO { 14 | 15 | private long id; 16 | 17 | private String username; 18 | 19 | private String password; 20 | 21 | private String email; 22 | 23 | @JsonIgnore 24 | private String salt = UUID.randomUUID().toString().replaceAll("-", ""); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/enums/Enable.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.enums; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | 6 | @AllArgsConstructor 7 | @Getter 8 | public enum Enable { 9 | 10 | TRUE(true, 1), FALSE(false, 0); 11 | 12 | private boolean enable; 13 | private int dbValue; 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/exceptions/TokenAuthExpiredException.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.exceptions; 2 | 3 | public class TokenAuthExpiredException extends RuntimeException { 4 | 5 | public TokenAuthExpiredException(String message) { 6 | super(message); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/interceptors/AuthHandlerInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.interceptors; 2 | 3 | import com.fengzhu.reading.exceptions.TokenAuthExpiredException; 4 | import com.fengzhu.reading.utils.BaseContext; 5 | import com.fengzhu.reading.utils.JwtUtils; 6 | import jakarta.servlet.http.HttpServletRequest; 7 | import jakarta.servlet.http.HttpServletResponse; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.beans.factory.annotation.Value; 11 | import org.springframework.stereotype.Component; 12 | import org.springframework.web.method.HandlerMethod; 13 | import org.springframework.web.servlet.HandlerInterceptor; 14 | 15 | import java.time.Instant; 16 | import java.util.Map; 17 | 18 | @Component 19 | @Slf4j 20 | public class AuthHandlerInterceptor implements HandlerInterceptor { 21 | 22 | @Autowired 23 | private JwtUtils jwtUtils; 24 | 25 | @Value("${jwt.token.refreshTime}") 26 | private Long refreshTime; 27 | 28 | @Value("${jwt.token.expiresTime}") 29 | private Long expiresTime; 30 | /** 31 | * 权限认证的拦截操作. 32 | */ 33 | @Override 34 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 35 | log.info("=======进入拦截器========"); 36 | // 如果不是映射到方法直接通过,可以访问资源. 37 | log.info("request url: " + request.getRequestURI()); 38 | if (!(handler instanceof HandlerMethod)) { 39 | return true; 40 | } 41 | //为空就返回错误 42 | String token = request.getHeader("token"); 43 | if (null == token || "".equals(token.trim())) { 44 | return false; 45 | } 46 | log.info("==============token:" + token); 47 | Map map = jwtUtils.parseToken(token); 48 | String userId = map.get("userId"); 49 | String userName = map.get("userName"); 50 | 51 | BaseContext.setCurrentId(Long.valueOf(userId)); 52 | long timeOfUse = Instant.now().toEpochMilli() - Long.parseLong(map.get("timeStamp")); 53 | //1.判断 token 是否过期 54 | if (timeOfUse < refreshTime) { 55 | log.info("token验证成功"); 56 | return true; 57 | } 58 | //超过token刷新时间,刷新 token 59 | else if (timeOfUse >= refreshTime && timeOfUse < expiresTime) { 60 | response.setHeader("token", jwtUtils.getToken(userId, userName)); 61 | log.info("token刷新成功"); 62 | return true; 63 | } 64 | //token过期就返回 token 无效. 65 | else { 66 | throw new TokenAuthExpiredException("token is invalid"); 67 | } 68 | } 69 | 70 | @Override 71 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 72 | HandlerInterceptor.super.afterCompletion(request, response, handler, ex); 73 | BaseContext.removeCurrentId(); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/interceptors/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.interceptors; 2 | 3 | import com.fengzhu.reading.CommonResponse; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.web.bind.annotation.ControllerAdvice; 6 | import org.springframework.web.bind.annotation.ExceptionHandler; 7 | import org.springframework.web.bind.annotation.ResponseBody; 8 | 9 | @ControllerAdvice 10 | @Slf4j 11 | public class GlobalExceptionHandler { 12 | 13 | @ExceptionHandler(value = Throwable.class) 14 | @ResponseBody 15 | public CommonResponse exceptionHandler(Throwable e){ 16 | log.error("catch uncaught exception", e); 17 | return CommonResponse.newFail("系统内部错误:" + e.getMessage(), null); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/repository/BookAvgRatingRepository.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.repository; 2 | 3 | import com.fengzhu.reading.dataObject.BookAvgRating; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.Optional; 9 | 10 | @Repository 11 | public interface BookAvgRatingRepository extends JpaRepository, JpaSpecificationExecutor { 12 | 13 | Optional findByBookIdAndEnable(long bookId, boolean enable); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/repository/BookESRepository.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.repository; 2 | 3 | import com.fengzhu.reading.dataObject.BookES; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.elasticsearch.annotations.Highlight; 7 | import org.springframework.data.elasticsearch.annotations.HighlightField; 8 | import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; 9 | import org.springframework.stereotype.Repository; 10 | 11 | @Repository 12 | public interface BookESRepository extends ElasticsearchRepository { 13 | 14 | @Highlight(fields = { 15 | @HighlightField(name = "book_name") 16 | }) 17 | Page findByBookNameOrIntroductionLike(String bookName, String introduction, Pageable pageable); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/repository/BookRatingRepository.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.repository; 2 | 3 | import com.fengzhu.reading.dataObject.BookRating; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.List; 9 | 10 | @Repository 11 | public interface BookRatingRepository extends JpaRepository, JpaSpecificationExecutor { 12 | 13 | List findByBookIdAndRateDateBetween(long bookId, long startTime, long endTime); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/repository/BookRepository.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.repository; 2 | 3 | import com.fengzhu.reading.dataObject.Book; 4 | import org.hibernate.annotations.DynamicUpdate; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import java.util.List; 10 | 11 | @Repository 12 | @DynamicUpdate 13 | public interface BookRepository extends JpaRepository, JpaSpecificationExecutor { 14 | 15 | List findByIdIn(List bookIds); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/repository/BookReviewRepository.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.repository; 2 | 3 | import com.fengzhu.reading.dataObject.BookReview; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 8 | import org.springframework.stereotype.Repository; 9 | 10 | @Repository 11 | public interface BookReviewRepository extends JpaRepository, JpaSpecificationExecutor { 12 | 13 | Page findByBookId(long bookId, Pageable pageable); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/repository/BookTagRepository.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.repository; 2 | 3 | import com.fengzhu.reading.dataObject.BookTag; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 8 | import org.springframework.data.jpa.repository.Query; 9 | import org.springframework.data.repository.query.Param; 10 | import org.springframework.stereotype.Repository; 11 | 12 | import java.util.List; 13 | 14 | @Repository 15 | public interface BookTagRepository extends JpaRepository, JpaSpecificationExecutor { 16 | 17 | void deleteByBookId(long bookId); 18 | 19 | @Query(value = "select * from book_tag where tag_group_id=:tagGroupId and tag_value & :tagValue > 0", nativeQuery = true) 20 | Page findByTag(@Param("tagGroupId") long tagGroupId, @Param("tagValue") long tagValue, Pageable pageable); 21 | 22 | List findByBookId(Long bookId); 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/repository/LikesStatisticRepository.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.repository; 2 | 3 | import com.fengzhu.reading.dataObject.LikesStatistic; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.Optional; 9 | 10 | @Repository 11 | public interface LikesStatisticRepository extends JpaRepository, JpaSpecificationExecutor { 12 | 13 | Optional findByBusinessIdAndItemId(long businessId, long itemId); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/repository/LikesUserRecordRepository.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.repository; 2 | 3 | import com.fengzhu.reading.dataObject.LikesUserRecord; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import java.util.List; 10 | import java.util.Optional; 11 | 12 | @Repository 13 | public interface LikesUserRecordRepository extends JpaRepository, JpaSpecificationExecutor { 14 | 15 | @Query(value = "select * from likes_user_record where user_id=:userId and business_id=:businessId and item_id=:itemId and likes>0", nativeQuery = true) 16 | Optional findUserLikeRecord(long userId, long businessId, long itemId); 17 | 18 | List findByUserIdAndBusinessIdAndLikes(long userId, Long businessId, boolean likes); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/repository/TagGroupRepository.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.repository; 2 | 3 | import com.fengzhu.reading.dataObject.TagGroup; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 6 | 7 | public interface TagGroupRepository extends JpaRepository, JpaSpecificationExecutor { 8 | 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/repository/TagRepository.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.repository; 2 | 3 | import com.fengzhu.reading.dataObject.Tag; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.stereotype.Repository; 8 | import org.springframework.web.bind.annotation.RequestParam; 9 | 10 | import java.util.List; 11 | import java.util.Optional; 12 | 13 | @Repository 14 | public interface TagRepository extends JpaRepository, JpaSpecificationExecutor { 15 | 16 | @Query(value = "select max(tag_value) from tag where tag_group_id = :tagGroupId", nativeQuery = true) 17 | Optional findMaxTagInGroup(@RequestParam("tagGroupId") long tagGroupId); 18 | 19 | List findByIdIn(List ids); 20 | 21 | List findByTagGroupId(long tagGroupId); 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.repository; 2 | 3 | import com.fengzhu.reading.dataObject.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.Optional; 9 | 10 | @Repository 11 | public interface UserRepository extends JpaRepository, JpaSpecificationExecutor { 12 | 13 | 14 | Optional findByUsername(String userName); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/BookAvgRatingService.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service; 2 | 3 | import com.fengzhu.reading.dto.BookAvgRatingDTO; 4 | 5 | public interface BookAvgRatingService { 6 | 7 | BookAvgRatingDTO getAvgRatingByBookId(long bookId); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/BookRatingService.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service; 2 | 3 | import com.fengzhu.reading.dto.BookAvgRatingDTO; 4 | import com.fengzhu.reading.dto.BookRatingDTO; 5 | 6 | public interface BookRatingService { 7 | 8 | long addNewBookRating(BookRatingDTO bookRatingDTO); 9 | 10 | BookAvgRatingDTO getBookAvgRatingByBookId(long bookId); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/BookReviewService.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service; 2 | 3 | import com.fengzhu.reading.dto.BookReviewDTO; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | 7 | public interface BookReviewService { 8 | 9 | long addNewBookReview(BookReviewDTO bookReviewDTO); 10 | 11 | Page getBookReviewDTOListByBookId(long bookId, Pageable pageable); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/BookService.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service; 2 | 3 | import com.fengzhu.reading.dto.BookDTO; 4 | import com.fengzhu.reading.dto.BookRankDTO; 5 | import com.fengzhu.reading.dto.TagDTO; 6 | import org.springframework.data.domain.Page; 7 | import org.springframework.data.domain.PageRequest; 8 | 9 | import java.util.List; 10 | 11 | public interface BookService { 12 | 13 | BookDTO addNewBook(BookDTO bookDTO); 14 | 15 | BookDTO updateBook(BookDTO bookDTO); 16 | 17 | Page lookupBooks(PageRequest pageRequest, Long tagId); 18 | 19 | BookDTO getBookDTOById(Long bookId); 20 | 21 | List getTagsByBookId(Long bookId); 22 | 23 | List getBookRank(int size); 24 | 25 | Page searchBooks(String keyword); 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/LikesService.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service; 2 | 3 | import com.fengzhu.reading.dto.LikesUserRecordDTO; 4 | 5 | import java.util.List; 6 | 7 | public interface LikesService { 8 | 9 | boolean addNewLikesRecord(LikesUserRecordDTO likesUserRecordDTO); 10 | 11 | List getMyLikes(long userId, Long businessId); 12 | 13 | Long getItemLikesCount(Long businessId, Long itemId); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/RabbitmqService.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service; 2 | 3 | import org.springframework.amqp.core.AmqpTemplate; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Component; 6 | import org.springframework.beans.factory.annotation.Value; 7 | 8 | @Component 9 | public class RabbitmqService { 10 | 11 | @Autowired 12 | private AmqpTemplate amqpTemplate; 13 | 14 | @Value("${rabbitmq.reading.exchange}") 15 | private String exchange; 16 | 17 | @Value("${rabbitmq.reading.routingkey}") 18 | private String routingkey; 19 | 20 | public void publishMessage(T type){ 21 | amqpTemplate.convertAndSend(exchange, routingkey, type); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/TagService.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service; 2 | 3 | import com.fengzhu.reading.dto.TagDTO; 4 | import com.fengzhu.reading.dto.TagGroupDTO; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | public interface TagService { 10 | 11 | TagDTO addNewTag(TagDTO tagDTO); 12 | 13 | TagDTO getTagDTOByTagId(Long tagId); 14 | 15 | Map> getAllTags(); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service; 2 | 3 | import com.fengzhu.reading.dto.UserDTO; 4 | 5 | public interface UserService { 6 | 7 | long registerUser(UserDTO userDTO); 8 | 9 | String login(String username, String password); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/impl/BookAvgRatingServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service.impl; 2 | 3 | import com.fengzhu.reading.converter.BookAvgRatingConverter; 4 | import com.fengzhu.reading.repository.BookAvgRatingRepository; 5 | import com.fengzhu.reading.dataObject.BookAvgRating; 6 | import com.fengzhu.reading.dto.BookAvgRatingDTO; 7 | import com.fengzhu.reading.enums.Enable; 8 | import com.fengzhu.reading.service.BookAvgRatingService; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Service; 11 | 12 | @Service 13 | public class BookAvgRatingServiceImpl implements BookAvgRatingService { 14 | 15 | @Autowired 16 | private BookAvgRatingRepository bookAvgRatingRepository; 17 | 18 | @Override 19 | public BookAvgRatingDTO getAvgRatingByBookId(long bookId) { 20 | BookAvgRating bookAvgRating = bookAvgRatingRepository.findByBookIdAndEnable(bookId, Enable.TRUE.isEnable()). 21 | orElseThrow(() -> new IllegalArgumentException("bookId不存在评分")); 22 | 23 | return BookAvgRatingConverter.convertToBookAvgRatingDTO(bookAvgRating); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/impl/BookRatingServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service.impl; 2 | 3 | import com.fengzhu.reading.converter.BookAvgRatingConverter; 4 | import com.fengzhu.reading.converter.BookRatingConverter; 5 | import com.fengzhu.reading.repository.BookAvgRatingRepository; 6 | import com.fengzhu.reading.repository.BookRatingRepository; 7 | import com.fengzhu.reading.dataObject.BookAvgRating; 8 | import com.fengzhu.reading.dataObject.BookRating; 9 | import com.fengzhu.reading.dto.BookAvgRatingDTO; 10 | import com.fengzhu.reading.dto.BookRatingDTO; 11 | import com.fengzhu.reading.enums.Enable; 12 | import com.fengzhu.reading.service.BookRatingService; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.stereotype.Service; 15 | import org.springframework.transaction.annotation.Transactional; 16 | 17 | @Service 18 | public class BookRatingServiceImpl implements BookRatingService { 19 | 20 | @Autowired 21 | private BookRatingRepository bookRatingRepository; 22 | 23 | @Autowired 24 | private BookAvgRatingRepository bookAvgRatingRepository; 25 | 26 | @Override 27 | @Transactional 28 | public long addNewBookRating(BookRatingDTO bookRatingDTO) { 29 | BookRating bookRating = BookRatingConverter.converToBookRating(bookRatingDTO); 30 | bookRating = bookRatingRepository.save(bookRating); 31 | return bookRating.getId(); 32 | } 33 | 34 | @Override 35 | public BookAvgRatingDTO getBookAvgRatingByBookId(long bookId) { 36 | BookAvgRating bookAvgRating = bookAvgRatingRepository.findByBookIdAndEnable(bookId, Enable.TRUE.isEnable()).orElse(null); 37 | return BookAvgRatingConverter.convertToBookAvgRatingDTO(bookAvgRating); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/impl/BookReviewServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service.impl; 2 | 3 | import com.fengzhu.reading.converter.BookReviewConverter; 4 | import com.fengzhu.reading.repository.BookReviewRepository; 5 | import com.fengzhu.reading.dataObject.BookReview; 6 | import com.fengzhu.reading.dto.BookReviewDTO; 7 | import com.fengzhu.reading.service.BookReviewService; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.data.domain.*; 10 | import org.springframework.stereotype.Service; 11 | import org.springframework.util.CollectionUtils; 12 | 13 | import java.util.List; 14 | 15 | @Service 16 | public class BookReviewServiceImpl implements BookReviewService { 17 | 18 | @Autowired 19 | private BookReviewRepository bookReviewRepository; 20 | 21 | @Override 22 | public long addNewBookReview(BookReviewDTO bookReviewDTO) { 23 | BookReview bookReview = BookReviewConverter.convertToBookReview(bookReviewDTO); 24 | bookReview = bookReviewRepository.save(bookReview); 25 | return bookReview.getBookId(); 26 | } 27 | 28 | @Override 29 | public Page getBookReviewDTOListByBookId(long bookId, Pageable pageable) { 30 | Page bookReviewPage = bookReviewRepository.findByBookId(bookId, pageable); 31 | if (CollectionUtils.isEmpty(bookReviewPage.getContent())) { 32 | return Page.empty(); 33 | } 34 | List bookReviewDTOList = bookReviewPage.getContent().stream() 35 | .map(BookReviewConverter::convertToBookReviewDTO) 36 | .toList(); 37 | return new PageImpl<>(bookReviewDTOList, pageable, bookReviewPage.getTotalElements()); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/impl/BookServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service.impl; 2 | 3 | import com.fengzhu.reading.converter.BookConverter; 4 | import com.fengzhu.reading.converter.TagConverter; 5 | import com.fengzhu.reading.dataObject.Book; 6 | import com.fengzhu.reading.dataObject.BookES; 7 | import com.fengzhu.reading.dataObject.BookTag; 8 | import com.fengzhu.reading.dataObject.Tag; 9 | import com.fengzhu.reading.dto.BookDTO; 10 | import com.fengzhu.reading.dto.BookRankDTO; 11 | import com.fengzhu.reading.dto.TagDTO; 12 | import com.fengzhu.reading.repository.BookESRepository; 13 | import com.fengzhu.reading.repository.BookRepository; 14 | import com.fengzhu.reading.repository.BookTagRepository; 15 | import com.fengzhu.reading.repository.TagRepository; 16 | import com.fengzhu.reading.service.BookService; 17 | import com.google.common.collect.Lists; 18 | import org.apache.commons.lang.StringUtils; 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | import org.springframework.data.domain.Page; 21 | import org.springframework.data.domain.PageImpl; 22 | import org.springframework.data.domain.PageRequest; 23 | import org.springframework.data.domain.Pageable; 24 | import org.springframework.data.redis.core.RedisTemplate; 25 | import org.springframework.data.redis.core.ZSetOperations; 26 | import org.springframework.stereotype.Service; 27 | import org.springframework.transaction.annotation.Transactional; 28 | import org.springframework.util.CollectionUtils; 29 | 30 | import java.util.*; 31 | import java.util.stream.Collectors; 32 | 33 | import static com.fengzhu.reading.Constants.BOOK_RANK_KEY; 34 | 35 | @Service 36 | public class BookServiceImpl implements BookService { 37 | 38 | @Autowired 39 | private BookRepository bookRepository; 40 | 41 | @Autowired 42 | private BookTagRepository bookTagRepository; 43 | 44 | @Autowired 45 | private TagRepository tagRepository; 46 | 47 | @Autowired 48 | private RedisTemplate redisTemplate; 49 | 50 | @Autowired 51 | private BookESRepository bookESRepository; 52 | 53 | 54 | @Override 55 | @Transactional 56 | public BookDTO addNewBook(BookDTO bookDTO) { 57 | Book book = BookConverter.convertToBook(bookDTO); 58 | book = bookRepository.save(book); 59 | 60 | BookDTO updatedBookDTO = BookConverter.converToBookDTO(book); 61 | if (!CollectionUtils.isEmpty(bookDTO.getTagDTOList())) { 62 | List updatedTagDTOs = saveBookTags(bookDTO.getTagDTOList(), book.getId()); 63 | updatedBookDTO.setTagDTOList(updatedTagDTOs); 64 | } 65 | return updatedBookDTO; 66 | } 67 | 68 | @Override 69 | @Transactional 70 | public BookDTO updateBook(BookDTO bookDTO) { 71 | if (bookDTO.getId() == 0L) { 72 | throw new IllegalArgumentException("book id is null"); 73 | } 74 | 75 | long bookId = bookDTO.getId(); 76 | Book originalBook = bookRepository.findById(bookId) 77 | .orElseThrow(() -> new IllegalArgumentException("book id not exist, " + bookId)); 78 | 79 | if (StringUtils.isNotEmpty(bookDTO.getBookName())) { 80 | originalBook.setBookName(bookDTO.getBookName()); 81 | } 82 | if (StringUtils.isNotEmpty(bookDTO.getAuthor())) { 83 | originalBook.setAuthor(bookDTO.getAuthor()); 84 | } 85 | if (StringUtils.isNotBlank(bookDTO.getIsbn())) { 86 | originalBook.setIsbn(bookDTO.getIsbn()); 87 | } 88 | if (StringUtils.isNotBlank(bookDTO.getIntroduction())) { 89 | originalBook.setIntroduction(bookDTO.getIntroduction()); 90 | } 91 | if (bookDTO.getPublishDate() != 0L) { 92 | originalBook.setPublishDate(bookDTO.getPublishDate()); 93 | } 94 | 95 | Book book = bookRepository.save(originalBook); 96 | BookDTO updatedBookDTO = BookConverter.converToBookDTO(book); 97 | if (!CollectionUtils.isEmpty(bookDTO.getTagDTOList())) { 98 | List updatedTagDTOS = saveBookTags(bookDTO.getTagDTOList(), bookId); 99 | updatedBookDTO.setTagDTOList(updatedTagDTOS); 100 | } 101 | 102 | return updatedBookDTO; 103 | } 104 | 105 | @Override 106 | public Page lookupBooks(PageRequest pageRequest, Long tagId) { 107 | if (tagId == null) { 108 | Page bookPage = bookRepository.findAll(pageRequest); 109 | return bookPage.map(BookConverter::converToBookDTO); 110 | } 111 | 112 | Tag tag = tagRepository.findById(tagId) 113 | .orElseThrow(() -> new IllegalArgumentException("tagId:" + tagId + " not found")); 114 | 115 | long tagGroupId = tag.getTagGroupId(); 116 | long tagValue = tag.getTagValue(); 117 | 118 | Page bookTagPage = bookTagRepository.findByTag(tagGroupId, tagValue, pageRequest); 119 | if (CollectionUtils.isEmpty(bookTagPage.getContent())) { 120 | return Page.empty(); 121 | } 122 | 123 | return bookTagPage 124 | .map(bookTag -> BookConverter.converToBookDTO(bookRepository.findById(bookTag.getBookId()).orElse(null))); 125 | 126 | } 127 | 128 | @Override 129 | public BookDTO getBookDTOById(Long bookId) { 130 | redisTemplate.opsForZSet().incrementScore(BOOK_RANK_KEY, String.valueOf(bookId), 1); 131 | Book book = bookRepository.findById(bookId).orElseThrow(() -> new IllegalArgumentException("bookId不存在")); 132 | BookDTO bookDTO = BookConverter.converToBookDTO(book); 133 | List tagDTOList = getTagsByBookId(bookId); 134 | bookDTO.setTagDTOList(tagDTOList); 135 | return bookDTO; 136 | } 137 | 138 | @Override 139 | public List getTagsByBookId(Long bookId) { 140 | List bookTagList = bookTagRepository.findByBookId(bookId); 141 | List allTagDTOList = Lists.newArrayList(); 142 | for (BookTag bookTag : bookTagList) { 143 | long tagGroupId = bookTag.getTagGroupId(); 144 | List tagList = tagRepository.findByTagGroupId(tagGroupId); 145 | List containsTagDTOList = tagList.stream() 146 | .filter(tag -> (tag.getTagValue() & bookTag.getTagValue()) == tag.getTagValue()) 147 | .filter(Objects::nonNull) 148 | .map(TagConverter::convertToTagDTO) 149 | .toList(); 150 | if (!CollectionUtils.isEmpty(containsTagDTOList)) { 151 | allTagDTOList.addAll(containsTagDTOList); 152 | } 153 | } 154 | return allTagDTOList; 155 | } 156 | 157 | @Override 158 | public List getBookRank(int size) { 159 | Set> rank = redisTemplate.opsForZSet().reverseRangeWithScores(BOOK_RANK_KEY, 0, size); 160 | List bookRankDTOList = Lists.newArrayList(); 161 | int order = 0; 162 | for (ZSetOperations.TypedTuple tuple : rank) { 163 | long bookId = Long.valueOf(tuple.getValue()); 164 | Book book = bookRepository.findById(bookId).orElse(null); 165 | BookRankDTO bookRankDTO = BookRankDTO.builder() 166 | .bookId(bookId) 167 | .bookName(book == null ? "" : book.getBookName()) 168 | .hit(tuple.getScore().longValue()) 169 | .order(++order).build(); 170 | 171 | bookRankDTOList.add(bookRankDTO); 172 | } 173 | return bookRankDTOList; 174 | } 175 | 176 | @Override 177 | public Page searchBooks(String keyword) { 178 | Pageable pageable = PageRequest.of(0, 10); 179 | Page bookESPage = bookESRepository.findByBookNameOrIntroductionLike(keyword, keyword, pageable); 180 | if (CollectionUtils.isEmpty(bookESPage.getContent())) { 181 | return Page.empty(); 182 | } 183 | 184 | List bookDTOList = bookESPage.getContent().stream().map(BookConverter::converToBookDTO).toList(); 185 | return new PageImpl<>(bookDTOList, pageable, bookESPage.getTotalElements()); 186 | } 187 | 188 | private List saveBookTags(List tagDTOList, long bookId) { 189 | Map> tagGroupMap = tagDTOList.stream() 190 | .collect(Collectors.groupingBy(TagDTO::getTagGroupId)); 191 | 192 | bookTagRepository.deleteByBookId(bookId); 193 | List bookTagList = new ArrayList(); 194 | for (Map.Entry> entry : tagGroupMap.entrySet()) { 195 | List tagDTOS = entry.getValue(); 196 | long tagValueInGroup = getTagValue(tagDTOS); 197 | 198 | BookTag bookTag = BookTag.builder() 199 | .bookId(bookId) 200 | .tagGroupId(entry.getKey()) 201 | .tagValue(tagValueInGroup) 202 | .build(); 203 | 204 | bookTagList.add(bookTag); 205 | } 206 | 207 | bookTagRepository.saveAll(bookTagList); 208 | List tagIds = tagDTOList.stream().map(tag -> tag.getId()).collect(Collectors.toList()); 209 | List updatedTags = tagRepository.findByIdIn(tagIds); 210 | return updatedTags.stream() 211 | .map(TagConverter::convertToTagDTO) 212 | .collect(Collectors.toList()); 213 | } 214 | 215 | private long getTagValue(List tagDTOS) { 216 | long tagValueInGroup = 0; 217 | for (TagDTO tagDTO : tagDTOS) { 218 | tagValueInGroup = tagValueInGroup | tagDTO.getTagValue(); 219 | } 220 | return tagValueInGroup; 221 | } 222 | 223 | } 224 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/impl/LikesServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service.impl; 2 | 3 | import com.fengzhu.reading.dataObject.LikesStatistic; 4 | import com.fengzhu.reading.dataObject.LikesUserRecord; 5 | import com.fengzhu.reading.dto.LikesUserRecordDTO; 6 | import com.fengzhu.reading.repository.LikesStatisticRepository; 7 | import com.fengzhu.reading.repository.LikesUserRecordRepository; 8 | import com.fengzhu.reading.service.LikesService; 9 | import com.fengzhu.reading.service.RabbitmqService; 10 | import com.google.common.collect.Lists; 11 | import lombok.extern.slf4j.Slf4j; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.data.redis.core.RedisTemplate; 14 | import org.springframework.stereotype.Service; 15 | 16 | import java.util.List; 17 | import java.util.Set; 18 | 19 | import static com.fengzhu.reading.Constants.LIKE_STATISTIC_KEY; 20 | import static com.fengzhu.reading.Constants.LIKE_USER_KEY; 21 | 22 | @Service 23 | @Slf4j 24 | public class LikesServiceImpl implements LikesService { 25 | 26 | @Autowired 27 | private RabbitmqService rabbitmqService; 28 | 29 | @Autowired 30 | private RedisTemplate redisTemplate; 31 | 32 | @Autowired 33 | private LikesUserRecordRepository likesUserRecordRepository; 34 | 35 | @Autowired 36 | private LikesStatisticRepository likesStatisticRepository; 37 | 38 | @Override 39 | public boolean addNewLikesRecord(LikesUserRecordDTO likesUserRecordDTO) { 40 | rabbitmqService.publishMessage(likesUserRecordDTO); 41 | return true; 42 | } 43 | 44 | @Override 45 | public List getMyLikes(long userId, Long businessId) { 46 | List likesItemIdList = Lists.newArrayList(); 47 | Set allMyLikes = redisTemplate.opsForSet().members(LIKE_USER_KEY + userId); 48 | if (allMyLikes != null && !allMyLikes.isEmpty()) { 49 | for (String like : allMyLikes) { 50 | likesItemIdList.add(Long.valueOf(like.split(":")[1])); 51 | } 52 | log.info("load my likes from cache: businessId:{}, userId:{}", businessId, userId); 53 | return likesItemIdList; 54 | } 55 | 56 | List likesUserRecordDTOList = likesUserRecordRepository 57 | .findByUserIdAndBusinessIdAndLikes(userId, businessId, true); 58 | 59 | log.info("load my likes from db: businessId:{}, userId:{}", businessId, userId); 60 | return likesUserRecordDTOList == null ? Lists.newArrayList() : 61 | likesUserRecordDTOList.stream().map(LikesUserRecord::getItemId).toList(); 62 | } 63 | 64 | @Override 65 | public Long getItemLikesCount(Long businessId, Long itemId) { 66 | String statisticKey = LIKE_STATISTIC_KEY + businessId + ":" + itemId; 67 | Long count = (Long) redisTemplate.opsForValue().get(statisticKey); 68 | if (count != null) { 69 | log.info("load item like count from cache: businessId:{}, itemId:{}", businessId, itemId); 70 | return count; 71 | } 72 | 73 | LikesStatistic likesStatistic = likesStatisticRepository.findByBusinessIdAndItemId(businessId, itemId).orElse(null); 74 | log.info("load item like count from db: businessId:{}, itemId:{}", businessId, itemId); 75 | return likesStatistic == null ? 0L : likesStatistic.getLikeCount(); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/impl/TagServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service.impl; 2 | 3 | import com.fengzhu.reading.converter.TagConverter; 4 | import com.fengzhu.reading.converter.TagGroupConverter; 5 | import com.fengzhu.reading.repository.TagGroupRepository; 6 | import com.fengzhu.reading.repository.TagRepository; 7 | import com.fengzhu.reading.dataObject.Tag; 8 | import com.fengzhu.reading.dataObject.TagGroup; 9 | import com.fengzhu.reading.dto.TagDTO; 10 | import com.fengzhu.reading.dto.TagGroupDTO; 11 | import com.fengzhu.reading.service.TagService; 12 | import com.google.common.collect.Maps; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.stereotype.Service; 15 | import org.springframework.util.CollectionUtils; 16 | 17 | import java.util.List; 18 | import java.util.Map; 19 | import java.util.stream.Collectors; 20 | 21 | @Service 22 | public class TagServiceImpl implements TagService { 23 | 24 | @Autowired 25 | private TagRepository tagRepository; 26 | 27 | @Autowired 28 | private TagGroupRepository tagGroupRepository; 29 | 30 | @Override 31 | public TagDTO addNewTag(TagDTO tagDTO) { 32 | Tag tag = TagConverter.convertToTag(tagDTO); 33 | 34 | long maxTagValue = tagRepository.findMaxTagInGroup(tagDTO.getTagGroupId()).orElse(0L); 35 | if (maxTagValue >= (Long.MAX_VALUE)) { 36 | throw new UnsupportedOperationException("tagGroupId:" + tagDTO.getTagGroupId() + " 下tag数量已满"); 37 | } 38 | tag.setTagValue(maxTagValue == 0L ? 1L : maxTagValue << 1); 39 | tag = tagRepository.save(tag); 40 | return TagConverter.convertToTagDTO(tag); 41 | } 42 | 43 | @Override 44 | public TagDTO getTagDTOByTagId(Long tagId) { 45 | Tag tag = tagRepository.findById(tagId) 46 | .orElseThrow(() -> new IllegalArgumentException("tagId:" + tagId + " not found")); 47 | 48 | return TagConverter.convertToTagDTO(tag); 49 | } 50 | 51 | @Override 52 | public Map> getAllTags() { 53 | List tagGroupList = tagGroupRepository.findAll(); 54 | List tagGroupDTOList = tagGroupList.stream() 55 | .map(TagGroupConverter::converToTagGroupDTO) 56 | .collect(Collectors.toList()); 57 | 58 | Map> map = Maps.newHashMap(); 59 | for (TagGroupDTO tagGroupDTO : tagGroupDTOList) { 60 | List tagList = tagRepository.findByTagGroupId(tagGroupDTO.getTagGroupId()); 61 | 62 | if (CollectionUtils.isEmpty(tagList)) { 63 | continue; 64 | } 65 | 66 | List tagDTOS = tagList.stream().map(TagConverter::convertToTagDTO).collect(Collectors.toList()); 67 | map.put(tagGroupDTO, tagDTOS); 68 | } 69 | return map; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.service.impl; 2 | 3 | import com.fengzhu.reading.converter.UserConverter; 4 | import com.fengzhu.reading.dataObject.User; 5 | import com.fengzhu.reading.dto.UserDTO; 6 | import com.fengzhu.reading.repository.UserRepository; 7 | import com.fengzhu.reading.service.UserService; 8 | import com.fengzhu.reading.utils.JwtUtils; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Service; 11 | import org.springframework.util.DigestUtils; 12 | 13 | @Service 14 | public class UserServiceImpl implements UserService { 15 | 16 | @Autowired 17 | private UserRepository userRepository; 18 | 19 | @Autowired 20 | private JwtUtils jwtUtils; 21 | 22 | @Override 23 | public long registerUser(UserDTO userDTO) { 24 | User user = UserConverter.converToUser(userDTO); 25 | String password = userDTO.getPassword(); 26 | String salt = userDTO.getSalt(); 27 | String md5Password = DigestUtils.md5DigestAsHex((password + salt).getBytes()); 28 | user.setPassword(md5Password); 29 | userRepository.save(user); 30 | return user.getId(); 31 | } 32 | 33 | @Override 34 | public String login(String userName, String password) { 35 | User user = userRepository.findByUsername(userName) 36 | .orElseThrow(() -> new IllegalArgumentException("userName:" + userName + " not found")); 37 | 38 | String md5Password = DigestUtils.md5DigestAsHex((password + user.getSalt()).getBytes()); 39 | if (!md5Password.equals(user.getPassword())) { 40 | throw new IllegalArgumentException("username and password not match"); 41 | } 42 | return jwtUtils.getToken(String.valueOf(user.getId()), user.getUsername()); 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/task/BookAvgScoreTask.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.task; 2 | 3 | import com.fengzhu.reading.dataObject.Book; 4 | import com.fengzhu.reading.dataObject.BookAvgRating; 5 | import com.fengzhu.reading.dataObject.BookRating; 6 | import com.fengzhu.reading.repository.BookAvgRatingRepository; 7 | import com.fengzhu.reading.repository.BookRatingRepository; 8 | import com.fengzhu.reading.repository.BookRepository; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.scheduling.annotation.Scheduled; 12 | import org.springframework.stereotype.Component; 13 | import org.springframework.util.CollectionUtils; 14 | 15 | import java.time.Duration; 16 | import java.time.Instant; 17 | import java.util.List; 18 | import java.util.concurrent.ArrayBlockingQueue; 19 | import java.util.concurrent.Executor; 20 | import java.util.concurrent.ThreadPoolExecutor; 21 | import java.util.concurrent.TimeUnit; 22 | 23 | @Component 24 | @Slf4j 25 | public class BookAvgScoreTask { 26 | 27 | @Autowired 28 | private BookRatingRepository bookRatingRepository; 29 | 30 | @Autowired 31 | private BookRepository bookRepository; 32 | 33 | @Autowired 34 | private BookAvgRatingRepository bookAvgRatingRepository; 35 | 36 | private Executor executor = new ThreadPoolExecutor(8, 20, 37 | 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100)); 38 | 39 | @Scheduled(cron = "0 0 * * * *") 40 | public void calculateBookScore() { 41 | List bookIdList = bookRepository.findAll().stream().map(Book::getId).toList(); 42 | Instant now = Instant.now(); 43 | long endTime = now.toEpochMilli(); 44 | long beginTime = now.minus(Duration.ofHours(1)).toEpochMilli(); 45 | for (Long bookId : bookIdList) { 46 | executor.execute(() -> { 47 | try { 48 | List bookRatingList = bookRatingRepository.findByBookIdAndRateDateBetween(bookId, beginTime, endTime); 49 | if (CollectionUtils.isEmpty(bookRatingList)) { 50 | return; 51 | } 52 | 53 | float averageScore = (float) bookRatingList.stream().map(BookRating::getScore) 54 | .mapToDouble(Double::valueOf).average().orElse(0.0); 55 | 56 | BookAvgRating lastAvgRating = bookAvgRatingRepository.findByBookIdAndEnable(bookId, true).orElse(null); 57 | lastAvgRating.setEnable(false); 58 | bookAvgRatingRepository.save(lastAvgRating); 59 | log.info("[calculateBookScore:] {}, last avg score update successful", bookId); 60 | BookAvgRating bookAvgRating = BookAvgRating.builder() 61 | .bookId(bookId) 62 | .avgRatingScore(averageScore) 63 | .enable(true).build(); 64 | 65 | bookAvgRatingRepository.save(bookAvgRating); 66 | log.info("[calculateBookScore:] {}, current avg score update successful", bookId); 67 | } catch (Throwable throwable) { 68 | log.error("calculateBookScore execute fail, {}", bookId, throwable); 69 | } 70 | 71 | }); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/utils/BaseContext.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.utils; 2 | 3 | public class BaseContext { 4 | 5 | public static ThreadLocal threadLocal = new ThreadLocal<>(); 6 | 7 | //从jwt拦截器中获取当前的id 8 | public static void setCurrentId(Long id) { 9 | threadLocal.set(id); 10 | } 11 | 12 | //获取后通过thread带到想要使用的地方使用 13 | public static Long getCurrentId() { 14 | return threadLocal.get(); 15 | } 16 | 17 | //删除当前thread的信息 18 | public static void removeCurrentId() { 19 | threadLocal.remove(); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/utils/JwtUtils.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.utils; 2 | 3 | import com.alibaba.google.common.collect.Maps; 4 | import com.auth0.jwt.JWT; 5 | import com.auth0.jwt.JWTCreator; 6 | import com.auth0.jwt.algorithms.Algorithm; 7 | import com.auth0.jwt.interfaces.DecodedJWT; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.stereotype.Component; 10 | 11 | import java.time.Instant; 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | 15 | @Component 16 | public class JwtUtils { 17 | 18 | @Value("jwt.token.secretkey") 19 | private String secretKey; 20 | 21 | public String getToken(String userId, String userName) { 22 | JWTCreator.Builder builder = JWT.create(); 23 | return builder.withClaim("userId", userId) 24 | .withClaim("userName", userName) 25 | .withClaim("timeStamp", Instant.now().toEpochMilli()) 26 | .sign(Algorithm.HMAC256(secretKey)); 27 | } 28 | 29 | public Map parseToken(String token) { 30 | HashMap map = Maps.newHashMap(); 31 | DecodedJWT decodedjwt = JWT.require(Algorithm.HMAC256(secretKey)) 32 | .build().verify(token); 33 | 34 | map.put("userId", decodedjwt.getClaim("userId").asString()); 35 | map.put("userName", decodedjwt.getClaim("userName").asString()); 36 | map.put("timeStamp", decodedjwt.getClaim("timeStamp").asLong().toString()); 37 | return map; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/validator/BookRatingValidator.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.validator; 2 | 3 | import com.fengzhu.reading.dto.BookRatingDTO; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | public class BookRatingValidator { 8 | 9 | public void validateAddNewBookRating(BookRatingDTO bookRatingDTO) { 10 | if (bookRatingDTO.getScore() == 0) { 11 | throw new IllegalArgumentException("score为空"); 12 | } 13 | if (bookRatingDTO.getUserId() == 0L) { 14 | throw new IllegalArgumentException("userId为空"); 15 | } 16 | if (bookRatingDTO.getBookId() == 0L) { 17 | throw new IllegalArgumentException("bookId为空"); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/validator/BookReviewValidator.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.validator; 2 | 3 | import com.fengzhu.reading.dto.BookReviewDTO; 4 | import org.apache.commons.lang.StringUtils; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Component 8 | public class BookReviewValidator { 9 | 10 | public void validateAddNewBookReview(BookReviewDTO bookReviewDTO) { 11 | if (bookReviewDTO.getBookId() == 0L) { 12 | throw new IllegalArgumentException("bookId为空"); 13 | } 14 | if (bookReviewDTO.getUserId() == 0L) { 15 | throw new IllegalArgumentException("userId为空"); 16 | } 17 | if (StringUtils.isEmpty(bookReviewDTO.getReviewContent())) { 18 | throw new IllegalArgumentException("书评内容为空"); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/validator/BookValidator.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.validator; 2 | 3 | import com.fengzhu.reading.dto.BookDTO; 4 | import org.apache.commons.lang.StringUtils; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Component 8 | public class BookValidator { 9 | 10 | public void validateAddNewBook(BookDTO bookDTO) { 11 | if (StringUtils.isEmpty(bookDTO.getBookName())) { 12 | throw new IllegalArgumentException("book name is empty"); 13 | } 14 | 15 | if (StringUtils.isEmpty(bookDTO.getAuthor())) { 16 | throw new IllegalArgumentException("book author is empty"); 17 | } 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/fengzhu/reading/validator/LikesValidator.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading.validator; 2 | 3 | import com.fengzhu.reading.dto.LikesUserRecordDTO; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | public class LikesValidator { 8 | 9 | public void validateAddNewBook(LikesUserRecordDTO likesUserRecordDTO) { 10 | if (likesUserRecordDTO.getUserId() == 0L) { 11 | throw new IllegalArgumentException("userId is empty"); 12 | } 13 | if (likesUserRecordDTO.getBusinessId() == 0L) { 14 | throw new IllegalArgumentException("businessId is empty"); 15 | } 16 | 17 | if (likesUserRecordDTO.getItemId() == 0L) { 18 | throw new IllegalArgumentException("itemId is empty"); 19 | } 20 | 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=9090 2 | 3 | spring.application.name=reading 4 | 5 | spring.datasource.url=jdbc:mysql://localhost:3306/reading?characterEncoding=utf-8 6 | spring.datasource.username=root 7 | spring.datasource.password= 8 | 9 | springdoc.swagger-ui.enabled=true 10 | 11 | spring.data.redis.host=localhost 12 | spring.data.redis.port=6379 13 | spring.data.redis.database=0 14 | 15 | spring.data.redis.jedis.pool.enabled=true 16 | spring.data.redis.jedis.pool.min-idle=0 17 | spring.data.redis.jedis.pool.time-between-eviction-runs= 18 | 19 | spring.data.elasticsearch.cluster-name=elasticsearch 20 | spring.data.elasticsearch.cluster-nodes=localhost:9200 21 | spring.data.elasticsearch.repositories.enabled=true 22 | 23 | 24 | jwt.token.refreshTime=3600000 25 | jwt.token.expiresTime=604800000 26 | jwt.token.secretKey=!~fa$@cad&# 27 | 28 | 29 | rabbitmq.reading.queue=reading 30 | rabbitmq.reading.exchange=reading_exchange 31 | rabbitmq.reading.routingkey=reading_routingkey 32 | 33 | rabbitmq.reading.dlq.queue=dlq_reading 34 | rabbitmq.reading.dlq.exchange=dlq_reading_exchange 35 | rabbitmq.reading.dlq.routingkey=dlq_reading_routingkey 36 | 37 | # Rabbit MQ server properties 38 | spring.rabbitmq.host=localhost 39 | spring.rabbitmq.port=5672 40 | spring.rabbitmq.username=guest 41 | spring.rabbitmq.password=guest 42 | spring.rabbitmq.listener.simple.retry.enabled=true 43 | spring.rabbitmq.listener.simple.retry.max-attempts=3 44 | spring.rabbitmq.listener.simple.retry.initial-interval=3000 -------------------------------------------------------------------------------- /src/test/java/com/fengzhu/reading/ReadingApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.fengzhu.reading; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class ReadingApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------