当前位置:   article > 正文

黑马头条day08实战_黑马头条day8平台管理

黑马头条day8平台管理

目录

一、平台管理前端

1.nginx配置

 二、登录及网关

1.网关

1.1 nacos配置

1.2 bootstrap.yaml

1.3 登录拦截认证

1.4 AppJwtUtil

1.5启动类

2.登录

1.1 nacos配置

1.2 WebMvcConfig

1.3 mvc拦截器 AdTokenInterceptor

1.4 controller 接口

1.5 service实现类 

3. 测试

三、敏感词

1.1 在model模块中创建实体类

1.2 controller接口

1.3 service接口

1.4 service实现类

1.5 测试

四、频道管理

1.1 实体类创建

1.2 controller接口

1.3 service接口

1.4 service实现类

1.5 测试


一、平台管理前端

1.nginx配置

在nginx的配置文件下新增 heima-leadnews-admin.conf 文件,注意将admin-web文件夹的地址修改为自己的。

  1. upstream heima-admin-gateway{
  2. server localhost:51603;
  3. }
  4. server {
  5. listen 8803;
  6. location / {
  7. root E:/FrameworkRevise/heima-leadnews/admin-web/;
  8. index index.html;
  9. }
  10. location ~/service_6001/(.*) {
  11. proxy_pass http://heima-admin-gateway/$1;
  12. proxy_set_header HOST $host; # 不改变源请求头的值
  13. proxy_pass_request_body on; #开启获取请求体
  14. proxy_pass_request_headers on; #开启获取请求头
  15. proxy_set_header X-Real-IP $remote_addr; # 记录真实发出请求的客户端IP
  16. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #记录代理信息
  17. }
  18. }

配置完成之后可以启动nginx访问localhost:8803试一下,友情提醒,老师给的说明文档中的界面截图跟他给的资料中前端的是不一样的。能访问到这个界面就可以。

 二、登录及网关

1.网关

创建heima-leadnews-admin模块,目录结构如下

1.1 nacos配置

在nacos中新增配置 leadnews-admin-gateway

  1. spring:
  2. cloud:
  3. gateway:
  4. globalcors:
  5. cors-configurations:
  6. '[/**]': # 匹配所有请求
  7. allowedOrigins: "*" #跨域处理 允许所有的域
  8. allowedMethods: # 支持的方法
  9. - GET
  10. - POST
  11. - PUT
  12. - DELETE
  13. routes:
  14. # 平台管理
  15. - id: admin
  16. uri: lb://leadnews-admin
  17. predicates:
  18. - Path=/admin/**
  19. filters:
  20. - StripPrefix= 1
  21. # 自媒体端
  22. - id: wemedia
  23. uri: lb://leadnews-wemedia
  24. predicates:
  25. - Path=/wemedia/**
  26. filters:
  27. - StripPrefix= 1
  28. # 用户端
  29. - id: user
  30. uri: lb://leadnews-user
  31. predicates:
  32. - Path=/user/**
  33. filters:
  34. - StripPrefix= 1
1.2 bootstrap.yaml
  1. server:
  2. port: 51603
  3. spring:
  4. application:
  5. name: leadnews-admin-gateway
  6. cloud:
  7. nacos:
  8. discovery:
  9. server-addr: 192.168.200.130:8848
  10. config:
  11. server-addr: 192.168.200.130:8848
  12. file-extension: yml
1.3 登录拦截认证

AuthorizeFilter.java

  1. package com.heima.admin.gateway.filter;
  2. import com.heima.admin.gateway.util.AppJwtUtil;
  3. import io.jsonwebtoken.Claims;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.apache.commons.lang.StringUtils;
  6. import org.springframework.cloud.gateway.filter.GatewayFilterChain;
  7. import org.springframework.cloud.gateway.filter.GlobalFilter;
  8. import org.springframework.core.Ordered;
  9. import org.springframework.http.HttpStatus;
  10. import org.springframework.http.server.reactive.ServerHttpRequest;
  11. import org.springframework.http.server.reactive.ServerHttpResponse;
  12. import org.springframework.stereotype.Component;
  13. import org.springframework.web.server.ServerWebExchange;
  14. import reactor.core.publisher.Mono;
  15. @Component
  16. @Slf4j
  17. public class AuthorizeFilter implements Ordered, GlobalFilter {
  18. @Override
  19. public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  20. //1.获取request和response对象
  21. ServerHttpRequest request = exchange.getRequest();
  22. ServerHttpResponse response = exchange.getResponse();
  23. //2.判断是否是登录
  24. if(request.getURI().getPath().contains("/login")){
  25. //放行
  26. return chain.filter(exchange);
  27. }
  28. //3.获取token
  29. String token = request.getHeaders().getFirst("token");
  30. //4.判断token是否存在
  31. if(StringUtils.isBlank(token)){
  32. response.setStatusCode(HttpStatus.UNAUTHORIZED);
  33. return response.setComplete();
  34. }
  35. //5.判断token是否有效
  36. try {
  37. Claims claimsBody = AppJwtUtil.getClaimsBody(token);
  38. //是否是过期
  39. int result = AppJwtUtil.verifyToken(claimsBody);
  40. if(result == 1 || result == 2){
  41. response.setStatusCode(HttpStatus.UNAUTHORIZED);
  42. return response.setComplete();
  43. }
  44. //获取用户信息
  45. Object userId = claimsBody.get("id");
  46. //存入hadder
  47. ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
  48. httpHeaders.add("userId", userId + "");
  49. }).build();
  50. //重置请求
  51. exchange.mutate().request(serverHttpRequest);
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. }
  55. //6.放行
  56. return chain.filter(exchange);
  57. }
  58. /**
  59. * 优先级设置 值越小 优先级越高
  60. * @return
  61. */
  62. @Override
  63. public int getOrder() {
  64. return 0;
  65. }
  66. }
1.4 AppJwtUtil

AppJwtUtil.java

  1. package com.heima.admin.gateway.util;
  2. import io.jsonwebtoken.*;
  3. import javax.crypto.SecretKey;
  4. import javax.crypto.spec.SecretKeySpec;
  5. import java.util.*;
  6. public class AppJwtUtil {
  7. // TOKEN的有效期一天(S)
  8. private static final int TOKEN_TIME_OUT = 3_600;
  9. // 加密KEY
  10. private static final String TOKEN_ENCRY_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";
  11. // 最小刷新间隔(S)
  12. private static final int REFRESH_TIME = 300;
  13. // 生产ID
  14. public static String getToken(Long id){
  15. Map<String, Object> claimMaps = new HashMap<>();
  16. claimMaps.put("id",id);
  17. long currentTime = System.currentTimeMillis();
  18. return Jwts.builder()
  19. .setId(UUID.randomUUID().toString())
  20. .setIssuedAt(new Date(currentTime)) //签发时间
  21. .setSubject("system") //说明
  22. .setIssuer("heima") //签发者信息
  23. .setAudience("app") //接收用户
  24. .compressWith(CompressionCodecs.GZIP) //数据压缩方式
  25. .signWith(SignatureAlgorithm.HS512, generalKey()) //加密方式
  26. .setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000)) //过期时间戳
  27. .addClaims(claimMaps) //cla信息
  28. .compact();
  29. }
  30. /**
  31. * 获取token中的claims信息
  32. *
  33. * @param token
  34. * @return
  35. */
  36. private static Jws<Claims> getJws(String token) {
  37. return Jwts.parser()
  38. .setSigningKey(generalKey())
  39. .parseClaimsJws(token);
  40. }
  41. /**
  42. * 获取payload body信息
  43. *
  44. * @param token
  45. * @return
  46. */
  47. public static Claims getClaimsBody(String token) {
  48. try {
  49. return getJws(token).getBody();
  50. }catch (ExpiredJwtException e){
  51. return null;
  52. }
  53. }
  54. /**
  55. * 获取hearder body信息
  56. *
  57. * @param token
  58. * @return
  59. */
  60. public static JwsHeader getHeaderBody(String token) {
  61. return getJws(token).getHeader();
  62. }
  63. /**
  64. * 是否过期
  65. *
  66. * @param claims
  67. * @return -1:有效,0:有效,1:过期,2:过期
  68. */
  69. public static int verifyToken(Claims claims) {
  70. if(claims==null){
  71. return 1;
  72. }
  73. try {
  74. claims.getExpiration()
  75. .before(new Date());
  76. // 需要自动刷新TOKEN
  77. if((claims.getExpiration().getTime()-System.currentTimeMillis())>REFRESH_TIME*1000){
  78. return -1;
  79. }else {
  80. return 0;
  81. }
  82. } catch (ExpiredJwtException ex) {
  83. return 1;
  84. }catch (Exception e){
  85. return 2;
  86. }
  87. }
  88. /**
  89. * 由字符串生成加密key
  90. *
  91. * @return
  92. */
  93. public static SecretKey generalKey() {
  94. byte[] encodedKey = Base64.getEncoder().encode(TOKEN_ENCRY_KEY.getBytes());
  95. SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
  96. return key;
  97. }
  98. public static void main(String[] args) {
  99. /* Map map = new HashMap();
  100. map.put("id","11");*/
  101. System.out.println(AppJwtUtil.getToken(1102L));
  102. Jws<Claims> jws = AppJwtUtil.getJws("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAADWLQQqEMAwA_5KzhURNt_qb1KZYQSi0wi6Lf9942NsMw3zh6AVW2DYmDGl2WabkZgreCaM6VXzhFBfJMcMARTqsxIG9Z888QLui3e3Tup5Pb81013KKmVzJTGo11nf9n8v4nMUaEY73DzTabjmDAAAA.4SuqQ42IGqCgBai6qd4RaVpVxTlZIWC826QA9kLvt9d-yVUw82gU47HDaSfOzgAcloZedYNNpUcd18Ne8vvjQA");
  103. Claims claims = jws.getBody();
  104. System.out.println(claims.get("id"));
  105. }
  106. }
1.5启动类
  1. package com.heima.admin.gateway;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  5. /**
  6. * @author Z-熙玉
  7. * @version 1.0
  8. */
  9. @SpringBootApplication
  10. @EnableDiscoveryClient
  11. public class AdminGatewayApplication {
  12. public static void main(String[] args) {
  13. SpringApplication.run(AdminGatewayApplication.class, args);
  14. }
  15. }

2.登录

创建heima-leadnews-admin模块,(之后的bootstrap配置都大致一样,就都省略了,参考之前的稍微改一下即可)导入资料中admin的sql文件。目录结构如下

1.1 nacos配置

新增nacos heima-leadnews-admin配置

  1. spring:
  2. redis:
  3. host: 192.168.200.130
  4. password: leadnews
  5. port: 6379
  6. kafka:
  7. bootstrap-servers: 192.168.200.130:9092
  8. producer:
  9. retries: 10
  10. key-serializer: org.apache.kafka.common.serialization.StringSerializer
  11. value-serializer: org.apache.kafka.common.serialization.StringSerializer
  12. datasource:
  13. driver-class-name: com.mysql.jdbc.Driver
  14. url: jdbc:mysql://192.168.200.130:3306/leadnews_admin?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
  15. username: root
  16. password: root
  17. # 设置Mapper接口所对应的XML文件位置,如果你在Mapper接口中有自定义方法,需要进行该配置
  18. mybatis-plus:
  19. mapper-locations: classpath*:mapper/*.xml
  20. # 设置别名包扫描路径,通过该属性可以给包中的类注册别名
  21. type-aliases-package: com.heima.model.admin.pojos
  22. minio:
  23. accessKey: minio
  24. secretKey: minio123
  25. bucket: leadnews
  26. endpoint: http://192.168.200.130:9000
  27. readPath: http://192.168.200.130:9000
  28. feign:
  29. # 开启feign对hystrix熔断降级的支持
  30. hystrix:
  31. enabled: true
  32. # 修改调用超时时间
  33. client:
  34. config:
  35. default:
  36. connectTimeout: 5000
  37. readTimeout: 5000
1.2 WebMvcConfig
  1. package com.heima.admin.config;
  2. import com.heima.admin.interceptor.AdTokenInterceptor;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  6. /**
  7. * @author Z-熙玉
  8. * @version 1.0
  9. */
  10. @Configuration
  11. public class WebMvcConfig implements WebMvcConfigurer {
  12. @Override
  13. public void addInterceptors(InterceptorRegistry registry) {
  14. registry.addInterceptor(new AdTokenInterceptor())
  15. .addPathPatterns("/**");
  16. }
  17. }
1.3 mvc拦截器 AdTokenInterceptor
  1. package com.heima.admin.interceptor;
  2. import com.heima.model.admin.pojos.AdUser;
  3. import com.heima.model.wemedia.pojos.WmUser;
  4. import com.heima.utils.thread.AdThreadLocalUtil;
  5. import com.heima.utils.thread.WmThreadLocalUtil;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.web.servlet.HandlerInterceptor;
  8. import org.springframework.web.servlet.ModelAndView;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. /**
  12. * @author Z-熙玉
  13. * @version 1.0
  14. */
  15. @Slf4j
  16. public class AdTokenInterceptor implements HandlerInterceptor {
  17. /**
  18. * 得到用户信息并且存入当前线程中
  19. * @param request
  20. * @param response
  21. * @param handler
  22. * @return
  23. * @throws Exception
  24. */
  25. @Override
  26. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  27. String userId = request.getHeader("userId");
  28. if (userId != null) {
  29. //存入到当前线程中
  30. AdUser adUser = new AdUser();
  31. adUser.setId(Integer.valueOf(userId));
  32. AdThreadLocalUtil.setUser(adUser);
  33. log.info("AdTokenInterceptor.存入AdThreadLocalUtil成功,adUserId={}",adUser.getId());
  34. }
  35. return true;
  36. }
  37. /**
  38. * 清理线程中的数据
  39. * @param request
  40. * @param response
  41. * @param handler
  42. * @param modelAndView
  43. * @throws Exception
  44. */
  45. @Override
  46. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  47. //AdThreadLocalUtil.clear();
  48. }
  49. /**
  50. * @param request
  51. * @param response
  52. * @param handler
  53. * @param ex
  54. * @throws Exception
  55. */
  56. @Override
  57. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  58. AdThreadLocalUtil.clear();;
  59. }
  60. }
1.4 controller 接口
  1. package com.heima.admin.controller.v1;
  2. import com.heima.admin.service.AdminUserService;
  3. import com.heima.model.admin.dtos.AdUserDto;
  4. import com.heima.model.common.dtos.ResponseResult;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.web.bind.annotation.PostMapping;
  7. import org.springframework.web.bind.annotation.RequestBody;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;
  10. /**
  11. * @author Z-熙玉
  12. * @version 1.0
  13. */
  14. @RestController
  15. @RequestMapping("/login")
  16. public class LoginController {
  17. @Autowired
  18. private AdminUserService adminUserService;
  19. @PostMapping("/in")
  20. public ResponseResult login(@RequestBody AdUserDto dto) {
  21. return adminUserService.login(dto);
  22. }
  23. }
1.5 service实现类 

AdminUserServiceImpl .java

  1. package com.heima.admin.service.impl;
  2. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  3. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  4. import com.heima.admin.mapper.AdminUserMapper;
  5. import com.heima.admin.service.AdminUserService;
  6. import com.heima.model.admin.dtos.AdUserDto;
  7. import com.heima.model.admin.pojos.AdUser;
  8. import com.heima.model.common.dtos.ResponseResult;
  9. import com.heima.model.common.enums.AppHttpCodeEnum;
  10. import com.heima.utils.common.AppJwtUtil;
  11. import lombok.extern.slf4j.Slf4j;
  12. import org.apache.commons.lang3.StringUtils;
  13. import org.springframework.stereotype.Service;
  14. import org.springframework.util.DigestUtils;
  15. import java.util.HashMap;
  16. import java.util.Map;
  17. /**
  18. * @author Z-熙玉
  19. * @version 1.0
  20. */
  21. @Service
  22. @Slf4j
  23. public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdUser> implements AdminUserService {
  24. /**
  25. * 管理端用户登录
  26. * @param dto
  27. * @return
  28. */
  29. @Override
  30. public ResponseResult login(AdUserDto dto) {
  31. //检查参数
  32. if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
  33. return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码为空");
  34. }
  35. //查询用户
  36. AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
  37. if (user == null) {
  38. return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户名不存在");
  39. }
  40. //对比密码
  41. String salt = user.getSalt();
  42. String pswd = dto.getPassword();
  43. pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
  44. if (pswd.equals(user.getPassword())) {
  45. //返回数据 jwt
  46. Map<String,Object> map = new HashMap<>();
  47. map.put("token", AppJwtUtil.getToken(user.getId().longValue()));
  48. user.setSalt("");
  49. user.setPassword("");
  50. map.put("user",user);
  51. return ResponseResult.okResult(map);
  52. } else {
  53. return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
  54. }
  55. }
  56. }

3. 测试

启动heima-leadnews-admin-gateway和heima-leadnews-admin进行登录测试,可以正常登录

三、敏感词

前置说明:敏感词功能在自媒体模块中进行完善,因为前端发送的请求是以wemedia为前缀的,所以会被网关路由到自媒体模块,我也不晓得为什么这么设计,不改前端的话只能这么做了。

1.1 在model模块中创建实体类

sensitiveDto.java

  1. package com.heima.model.admin.dtos;
  2. import com.heima.model.common.dtos.PageRequestDto;
  3. import lombok.Data;
  4. /**
  5. * @author Z-熙玉
  6. * @version 1.0
  7. */
  8. @Data
  9. public class SensitiveDto extends PageRequestDto {
  10. private String name;
  11. }

WmSensitive.java

  1. package com.heima.model.wemedia.pojos;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import lombok.Data;
  7. import java.io.Serializable;
  8. import java.util.Date;
  9. /**
  10. * <p>
  11. * 敏感词信息表
  12. * </p>
  13. *
  14. * @author itheima
  15. */
  16. @Data
  17. @TableName("wm_sensitive")
  18. public class WmSensitive implements Serializable {
  19. private static final long serialVersionUID = 1L;
  20. /**
  21. * 主键
  22. */
  23. @TableId(value = "id", type = IdType.AUTO)
  24. private Integer id;
  25. /**
  26. * 敏感词
  27. */
  28. @TableField("sensitives")
  29. private String sensitives;
  30. /**
  31. * 创建时间
  32. */
  33. @TableField("created_time")
  34. private Date createdTime;
  35. }
1.2 controller接口

WmSensitiveController.java

  1. package com.heima.wemedia.controller.v1;
  2. import com.heima.model.admin.dtos.SensitiveDto;
  3. import com.heima.model.admin.pojos.AdSensitive;
  4. import com.heima.model.common.dtos.ResponseResult;
  5. import com.heima.wemedia.service.WmSensitiveService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.*;
  8. /**
  9. * @author Z-熙玉
  10. * @version 1.0
  11. */
  12. @RestController
  13. @RequestMapping("/api/v1/sensitive")
  14. public class WmSensitiveController {
  15. @Autowired
  16. private WmSensitiveService wmSensitiveService;
  17. @PostMapping("/list")
  18. public ResponseResult list(@RequestBody SensitiveDto dto) {
  19. return wmSensitiveService.findList(dto);
  20. }
  21. @DeleteMapping("/del/{id}")
  22. public ResponseResult del(@PathVariable("id") Integer id) {
  23. return wmSensitiveService.delSensitive(id);
  24. }
  25. @PostMapping("/save")
  26. public ResponseResult save(@RequestBody AdSensitive adSensitive) {
  27. return wmSensitiveService.saveSensitive(adSensitive);
  28. }
  29. @PostMapping("/update")
  30. public ResponseResult update(@RequestBody AdSensitive adSensitive) {
  31. return wmSensitiveService.updateSensitive(adSensitive);
  32. }
  33. }
1.3 service接口

WmSensitiveService.java

  1. package com.heima.wemedia.service;
  2. import com.baomidou.mybatisplus.extension.service.IService;
  3. import com.heima.model.admin.dtos.SensitiveDto;
  4. import com.heima.model.admin.pojos.AdSensitive;
  5. import com.heima.model.common.dtos.ResponseResult;
  6. import com.heima.model.wemedia.pojos.WmSensitive;
  7. /**
  8. * @author Z-熙玉
  9. * @version 1.0
  10. */
  11. public interface WmSensitiveService extends IService<WmSensitive> {
  12. /**
  13. * 敏感词列表
  14. * @param dto
  15. * @return
  16. */
  17. ResponseResult findList(SensitiveDto dto);
  18. /**
  19. * 根据id删除敏感词信息
  20. * @param id
  21. * @return
  22. */
  23. ResponseResult delSensitive(Integer id);
  24. /**
  25. * 保存敏感词
  26. * @param adSensitive
  27. * @return
  28. */
  29. ResponseResult saveSensitive(AdSensitive adSensitive);
  30. /**
  31. * 更新敏感词信息
  32. * @param adSensitive
  33. * @return
  34. */
  35. ResponseResult updateSensitive(AdSensitive adSensitive);
  36. }
1.4 service实现类

WmSensitiveServiceImpl.java

  1. package com.heima.wemedia.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.core.metadata.IPage;
  4. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  5. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  6. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  7. import com.heima.model.admin.dtos.SensitiveDto;
  8. import com.heima.model.admin.pojos.AdSensitive;
  9. import com.heima.model.common.dtos.PageResponseResult;
  10. import com.heima.model.common.dtos.ResponseResult;
  11. import com.heima.model.common.enums.AppHttpCodeEnum;
  12. import com.heima.model.wemedia.pojos.WmChannel;
  13. import com.heima.model.wemedia.pojos.WmSensitive;
  14. import com.heima.wemedia.mapper.WmSensitiveMapper;
  15. import com.heima.wemedia.service.WmSensitiveService;
  16. import lombok.extern.slf4j.Slf4j;
  17. import org.apache.commons.lang3.StringUtils;
  18. import org.springframework.beans.BeanUtils;
  19. import org.springframework.stereotype.Service;
  20. import java.util.Date;
  21. /**
  22. * @author Z-熙玉
  23. * @version 1.0
  24. */
  25. @Service
  26. @Slf4j
  27. public class WmSensitiveServiceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive> implements WmSensitiveService {
  28. /**
  29. * 敏感词分页条件查询
  30. * @param dto
  31. * @return
  32. */
  33. @Override
  34. public ResponseResult findList(SensitiveDto dto) {
  35. //检查参数
  36. dto.checkParam();
  37. //分页查询
  38. IPage page = new Page(dto.getPage(), dto.getSize());
  39. LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
  40. //按照创建时间倒序查询
  41. queryWrapper.orderByDesc(WmSensitive::getCreatedTime);
  42. //按照敏感词模糊查询
  43. if (StringUtils.isNotBlank(dto.getName())) {
  44. queryWrapper.like(WmSensitive::getSensitives, dto.getName());
  45. }
  46. page = page(page, queryWrapper);
  47. //返回结果
  48. ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
  49. responseResult.setData(page.getRecords());
  50. return responseResult;
  51. }
  52. /**
  53. * 根据id删除敏感词信息
  54. * @param id
  55. * @return
  56. */
  57. @Override
  58. public ResponseResult delSensitive(Integer id) {
  59. //校验参数
  60. if (id == null) {
  61. return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
  62. }
  63. //查询数据是否存在
  64. WmSensitive wmSensitive = getById(id);
  65. if (wmSensitive == null) {
  66. return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
  67. }
  68. //根据id删除
  69. removeById(id);
  70. return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
  71. }
  72. /**
  73. * 保存敏感词
  74. * @param adSensitive
  75. * @return
  76. */
  77. @Override
  78. public ResponseResult saveSensitive(AdSensitive adSensitive) {
  79. //参数校验
  80. if (adSensitive == null) {
  81. return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
  82. }
  83. //属性拷贝
  84. WmSensitive wmSensitive = new WmSensitive();
  85. BeanUtils.copyProperties(adSensitive, wmSensitive);
  86. //判断敏感词是否已经存在
  87. WmSensitive sensitive = getOne(Wrappers.<WmSensitive>lambdaQuery()
  88. .eq(WmSensitive::getSensitives, adSensitive.getSensitives()));
  89. if (sensitive != null) {
  90. return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
  91. }
  92. wmSensitive.setCreatedTime(new Date());
  93. save(wmSensitive);
  94. return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
  95. }
  96. /**
  97. * 更新敏感词信息
  98. * @param adSensitive
  99. * @return
  100. */
  101. @Override
  102. public ResponseResult updateSensitive(AdSensitive adSensitive) {
  103. //校验参数
  104. if (adSensitive == null) {
  105. return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
  106. }
  107. //属性拷贝
  108. WmSensitive wmSensitive = new WmSensitive();
  109. BeanUtils.copyProperties(adSensitive, wmSensitive);
  110. //修改信息
  111. updateById(wmSensitive);
  112. return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
  113. }
  114. }
1.5 测试

启动admin和wemedia以及他们的网关,以及schedule模块进行测试。

四、频道管理

这部分还是在自媒体模块当中完成。提醒:在频道分页查询中,在接口文档中所示,channelDto并没有status参数,也就是不能根据状态进行精确查询,小伙伴们可以自己在channelDto中加上status属性,试一下可不可以根据状态进行精确查询

1.1 实体类创建

channelDto

  1. package com.heima.model.admin.dtos;
  2. import com.heima.model.common.dtos.PageRequestDto;
  3. import lombok.Data;
  4. /**
  5. * @author Z-熙玉
  6. * @version 1.0
  7. */
  8. @Data
  9. public class ChannelDto extends PageRequestDto {
  10. /**
  11. * 频道名称
  12. */
  13. private String name;
  14. }

AdChannel

  1. package com.heima.model.admin.pojos;
  2. import com.heima.model.wemedia.pojos.WmChannel;
  3. /**
  4. * @author Z-熙玉
  5. * @version 1.0
  6. */
  7. public class AdChannel extends WmChannel {
  8. }
1.2 controller接口

WmChannelController

  1. package com.heima.wemedia.controller.v1;
  2. import com.heima.model.admin.dtos.ChannelDto;
  3. import com.heima.model.admin.pojos.AdChannel;
  4. import com.heima.model.common.dtos.ResponseResult;
  5. import com.heima.wemedia.service.WmChannelService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.*;
  8. /**
  9. * @author Z-熙玉
  10. * @version 1.0
  11. */
  12. @RestController
  13. @RequestMapping("/api/v1/channel")
  14. public class WmChannelController {
  15. @Autowired
  16. private WmChannelService wmChannelService;
  17. @GetMapping("/channels")
  18. public ResponseResult findAll() {
  19. return wmChannelService.findAll();
  20. }
  21. @PostMapping("/list")
  22. public ResponseResult list(@RequestBody ChannelDto dto) {
  23. return wmChannelService.findList(dto);
  24. }
  25. @PostMapping("/save")
  26. public ResponseResult save(@RequestBody AdChannel adChannel) {
  27. return wmChannelService.saveChannel(adChannel);
  28. }
  29. @PostMapping("/update")
  30. public ResponseResult update(@RequestBody AdChannel adChannel) {
  31. return wmChannelService.updateChannel(adChannel);
  32. }
  33. @GetMapping("/del/{id}")
  34. public ResponseResult del(@PathVariable("id") Integer id) {
  35. return wmChannelService.deleteChannel(id);
  36. }
  37. }
1.3 service接口

WmChannelService

  1. package com.heima.wemedia.service;
  2. import com.baomidou.mybatisplus.extension.service.IService;
  3. import com.heima.model.admin.dtos.ChannelDto;
  4. import com.heima.model.admin.pojos.AdChannel;
  5. import com.heima.model.common.dtos.ResponseResult;
  6. import com.heima.model.wemedia.pojos.WmChannel;
  7. public interface WmChannelService extends IService<WmChannel> {
  8. /**
  9. * 查询所有频道
  10. * @return
  11. */
  12. ResponseResult findAll();
  13. /**
  14. * 根据条件查询频道
  15. * @param dto
  16. * @return
  17. */
  18. ResponseResult findList(ChannelDto dto);
  19. /**
  20. * 新增频道
  21. * @param adChannel
  22. * @return
  23. */
  24. ResponseResult saveChannel(AdChannel adChannel);
  25. /**
  26. * 修改频道信息
  27. * @param adChannel
  28. * @return
  29. */
  30. ResponseResult updateChannel(AdChannel adChannel);
  31. /**
  32. * 根据id删除频道信息
  33. * @param id
  34. * @return
  35. */
  36. ResponseResult deleteChannel(Integer id);
  37. }
1.4 service实现类

WmChannelServiceImpl

  1. package com.heima.wemedia.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.core.metadata.IPage;
  4. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  5. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  6. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  7. import com.heima.model.admin.dtos.ChannelDto;
  8. import com.heima.model.admin.pojos.AdChannel;
  9. import com.heima.model.common.dtos.PageResponseResult;
  10. import com.heima.model.common.dtos.ResponseResult;
  11. import com.heima.model.common.enums.AppHttpCodeEnum;
  12. import com.heima.model.wemedia.pojos.WmChannel;
  13. import com.heima.model.wemedia.pojos.WmNews;
  14. import com.heima.wemedia.mapper.WmChannelMapper;
  15. import com.heima.wemedia.mapper.WmNewsMapper;
  16. import com.heima.wemedia.service.WmChannelService;
  17. import lombok.extern.slf4j.Slf4j;
  18. import org.apache.commons.lang3.StringUtils;
  19. import org.springframework.beans.BeanUtils;
  20. import org.springframework.beans.factory.annotation.Autowired;
  21. import org.springframework.stereotype.Service;
  22. import org.springframework.transaction.annotation.Transactional;
  23. import java.util.Date;
  24. @Service
  25. @Transactional
  26. @Slf4j
  27. public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {
  28. /**
  29. * 查询所有频道
  30. * @return
  31. */
  32. @Override
  33. public ResponseResult findAll() {
  34. return ResponseResult.okResult(list());
  35. }
  36. /**
  37. * 频道条件分页查询
  38. * @param dto
  39. * @return
  40. */
  41. public ResponseResult findList(ChannelDto dto) {
  42. //检查参数
  43. dto.checkParam();
  44. //分页条件查询
  45. IPage page = new Page(dto.getPage(),dto.getSize());
  46. LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
  47. //按照时间倒序查询
  48. queryWrapper.orderByDesc(WmChannel::getCreatedTime);
  49. //根据名称模糊查询
  50. if (StringUtils.isNotBlank(dto.getName())) {
  51. queryWrapper.like(WmChannel::getName, dto.getName());
  52. }
  53. // TODO 根据状态精确查询
  54. //根据默认排序进行排序
  55. queryWrapper.orderByAsc(WmChannel::getOrd);
  56. page = page(page, queryWrapper);
  57. //返回结果
  58. ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
  59. responseResult.setData(page.getRecords());
  60. return responseResult;
  61. }
  62. /**
  63. * 新增频道
  64. * @param adChannel
  65. * @return
  66. */
  67. @Override
  68. public ResponseResult saveChannel(AdChannel adChannel) {
  69. //属性拷贝
  70. WmChannel wmChannel = new WmChannel();
  71. BeanUtils.copyProperties(adChannel, wmChannel);
  72. //判断名称是否重复
  73. LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
  74. queryWrapper.eq(WmChannel::getName, wmChannel.getName());
  75. int count = count(queryWrapper);
  76. if (count > 0) {
  77. return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"频道名称已存在");
  78. }
  79. //设置默认属性值
  80. wmChannel.setOrd(1);
  81. wmChannel.setCreatedTime(new Date());
  82. wmChannel.setIsDefault(true);
  83. //保存数据
  84. save(wmChannel);
  85. return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(),"新增频道成功");
  86. }
  87. @Autowired
  88. private WmNewsMapper wmNewsMapper;
  89. /**
  90. * 修改频道信息
  91. * @param adChannel
  92. * @return
  93. */
  94. @Override
  95. public ResponseResult updateChannel(AdChannel adChannel) {
  96. //属性拷贝
  97. WmChannel wmChannel = new WmChannel();
  98. BeanUtils.copyProperties(adChannel, wmChannel);
  99. //判断当前频道是否被引用
  100. Integer count = wmNewsMapper
  101. .selectCount(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getChannelId, wmChannel.getId()));
  102. if (count > 0) {
  103. return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"该频道已被引用不能禁用");
  104. }
  105. updateById(wmChannel);
  106. return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
  107. }
  108. /**
  109. * 根据id删除频道信息
  110. * @param id
  111. * @return
  112. */
  113. @Override
  114. public ResponseResult deleteChannel(Integer id) {
  115. //校验参数
  116. if (id == null) {
  117. return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
  118. }
  119. //判断是否被禁用
  120. WmChannel wmChannel = getById(id);
  121. if (wmChannel.getStatus()) {
  122. return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"频道启用中无法删除");
  123. }
  124. removeById(id);
  125. return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
  126. }
  127. }
1.5 测试

用户审核和自媒体文章审核明天更新哦,这两部分内容偏多,明天准时更新哦。有什么问题,可以在评论区留言。最后可以的话,点赞加关注支持一下吧~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/988036
推荐阅读
相关标签
  

闽ICP备14008679号