赞
踩
目录
在nginx的配置文件下新增 heima-leadnews-admin.conf 文件,注意将admin-web文件夹的地址修改为自己的。
- upstream heima-admin-gateway{
- server localhost:51603;
- }
-
- server {
- listen 8803;
- location / {
- root E:/FrameworkRevise/heima-leadnews/admin-web/;
- index index.html;
- }
-
- location ~/service_6001/(.*) {
- proxy_pass http://heima-admin-gateway/$1;
- proxy_set_header HOST $host; # 不改变源请求头的值
- proxy_pass_request_body on; #开启获取请求体
- proxy_pass_request_headers on; #开启获取请求头
- proxy_set_header X-Real-IP $remote_addr; # 记录真实发出请求的客户端IP
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #记录代理信息
- }
- }
配置完成之后可以启动nginx访问localhost:8803试一下,友情提醒,老师给的说明文档中的界面截图跟他给的资料中前端的是不一样的。能访问到这个界面就可以。
创建heima-leadnews-admin模块,目录结构如下
在nacos中新增配置 leadnews-admin-gateway
- spring:
- cloud:
- gateway:
- globalcors:
- cors-configurations:
- '[/**]': # 匹配所有请求
- allowedOrigins: "*" #跨域处理 允许所有的域
- allowedMethods: # 支持的方法
- - GET
- - POST
- - PUT
- - DELETE
- routes:
- # 平台管理
- - id: admin
- uri: lb://leadnews-admin
- predicates:
- - Path=/admin/**
- filters:
- - StripPrefix= 1
- # 自媒体端
- - id: wemedia
- uri: lb://leadnews-wemedia
- predicates:
- - Path=/wemedia/**
- filters:
- - StripPrefix= 1
- # 用户端
- - id: user
- uri: lb://leadnews-user
- predicates:
- - Path=/user/**
- filters:
- - StripPrefix= 1
- server:
- port: 51603
- spring:
- application:
- name: leadnews-admin-gateway
- cloud:
- nacos:
- discovery:
- server-addr: 192.168.200.130:8848
- config:
- server-addr: 192.168.200.130:8848
- file-extension: yml
AuthorizeFilter.java
- package com.heima.admin.gateway.filter;
-
- import com.heima.admin.gateway.util.AppJwtUtil;
- import io.jsonwebtoken.Claims;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.lang.StringUtils;
- import org.springframework.cloud.gateway.filter.GatewayFilterChain;
- import org.springframework.cloud.gateway.filter.GlobalFilter;
- import org.springframework.core.Ordered;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.server.reactive.ServerHttpRequest;
- import org.springframework.http.server.reactive.ServerHttpResponse;
- import org.springframework.stereotype.Component;
- import org.springframework.web.server.ServerWebExchange;
- import reactor.core.publisher.Mono;
-
- @Component
- @Slf4j
- public class AuthorizeFilter implements Ordered, GlobalFilter {
- @Override
- public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
- //1.获取request和response对象
- ServerHttpRequest request = exchange.getRequest();
- ServerHttpResponse response = exchange.getResponse();
-
- //2.判断是否是登录
- if(request.getURI().getPath().contains("/login")){
- //放行
- return chain.filter(exchange);
- }
-
- //3.获取token
- String token = request.getHeaders().getFirst("token");
-
- //4.判断token是否存在
- if(StringUtils.isBlank(token)){
- response.setStatusCode(HttpStatus.UNAUTHORIZED);
- return response.setComplete();
- }
-
- //5.判断token是否有效
- try {
- Claims claimsBody = AppJwtUtil.getClaimsBody(token);
- //是否是过期
- int result = AppJwtUtil.verifyToken(claimsBody);
- if(result == 1 || result == 2){
- response.setStatusCode(HttpStatus.UNAUTHORIZED);
- return response.setComplete();
- }
- //获取用户信息
- Object userId = claimsBody.get("id");
- //存入hadder
- ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
- httpHeaders.add("userId", userId + "");
- }).build();
- //重置请求
- exchange.mutate().request(serverHttpRequest);
-
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- //6.放行
- return chain.filter(exchange);
- }
-
- /**
- * 优先级设置 值越小 优先级越高
- * @return
- */
- @Override
- public int getOrder() {
- return 0;
- }
- }
AppJwtUtil.java
- package com.heima.admin.gateway.util;
-
- import io.jsonwebtoken.*;
-
- import javax.crypto.SecretKey;
- import javax.crypto.spec.SecretKeySpec;
- import java.util.*;
-
- public class AppJwtUtil {
-
- // TOKEN的有效期一天(S)
- private static final int TOKEN_TIME_OUT = 3_600;
- // 加密KEY
- private static final String TOKEN_ENCRY_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";
- // 最小刷新间隔(S)
- private static final int REFRESH_TIME = 300;
-
- // 生产ID
- public static String getToken(Long id){
- Map<String, Object> claimMaps = new HashMap<>();
- claimMaps.put("id",id);
- long currentTime = System.currentTimeMillis();
- return Jwts.builder()
- .setId(UUID.randomUUID().toString())
- .setIssuedAt(new Date(currentTime)) //签发时间
- .setSubject("system") //说明
- .setIssuer("heima") //签发者信息
- .setAudience("app") //接收用户
- .compressWith(CompressionCodecs.GZIP) //数据压缩方式
- .signWith(SignatureAlgorithm.HS512, generalKey()) //加密方式
- .setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000)) //过期时间戳
- .addClaims(claimMaps) //cla信息
- .compact();
- }
-
- /**
- * 获取token中的claims信息
- *
- * @param token
- * @return
- */
- private static Jws<Claims> getJws(String token) {
- return Jwts.parser()
- .setSigningKey(generalKey())
- .parseClaimsJws(token);
- }
-
- /**
- * 获取payload body信息
- *
- * @param token
- * @return
- */
- public static Claims getClaimsBody(String token) {
- try {
- return getJws(token).getBody();
- }catch (ExpiredJwtException e){
- return null;
- }
- }
-
- /**
- * 获取hearder body信息
- *
- * @param token
- * @return
- */
- public static JwsHeader getHeaderBody(String token) {
- return getJws(token).getHeader();
- }
-
- /**
- * 是否过期
- *
- * @param claims
- * @return -1:有效,0:有效,1:过期,2:过期
- */
- public static int verifyToken(Claims claims) {
- if(claims==null){
- return 1;
- }
- try {
- claims.getExpiration()
- .before(new Date());
- // 需要自动刷新TOKEN
- if((claims.getExpiration().getTime()-System.currentTimeMillis())>REFRESH_TIME*1000){
- return -1;
- }else {
- return 0;
- }
- } catch (ExpiredJwtException ex) {
- return 1;
- }catch (Exception e){
- return 2;
- }
- }
-
- /**
- * 由字符串生成加密key
- *
- * @return
- */
- public static SecretKey generalKey() {
- byte[] encodedKey = Base64.getEncoder().encode(TOKEN_ENCRY_KEY.getBytes());
- SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
- return key;
- }
-
- public static void main(String[] args) {
- /* Map map = new HashMap();
- map.put("id","11");*/
- System.out.println(AppJwtUtil.getToken(1102L));
- Jws<Claims> jws = AppJwtUtil.getJws("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAADWLQQqEMAwA_5KzhURNt_qb1KZYQSi0wi6Lf9942NsMw3zh6AVW2DYmDGl2WabkZgreCaM6VXzhFBfJMcMARTqsxIG9Z888QLui3e3Tup5Pb81013KKmVzJTGo11nf9n8v4nMUaEY73DzTabjmDAAAA.4SuqQ42IGqCgBai6qd4RaVpVxTlZIWC826QA9kLvt9d-yVUw82gU47HDaSfOzgAcloZedYNNpUcd18Ne8vvjQA");
- Claims claims = jws.getBody();
- System.out.println(claims.get("id"));
-
- }
-
- }
- package com.heima.admin.gateway;
-
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
-
- /**
- * @author Z-熙玉
- * @version 1.0
- */
- @SpringBootApplication
- @EnableDiscoveryClient
- public class AdminGatewayApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(AdminGatewayApplication.class, args);
- }
- }
创建heima-leadnews-admin模块,(之后的bootstrap配置都大致一样,就都省略了,参考之前的稍微改一下即可)导入资料中admin的sql文件。目录结构如下
新增nacos heima-leadnews-admin配置
- spring:
- redis:
- host: 192.168.200.130
- password: leadnews
- port: 6379
- kafka:
- bootstrap-servers: 192.168.200.130:9092
- producer:
- retries: 10
- key-serializer: org.apache.kafka.common.serialization.StringSerializer
- value-serializer: org.apache.kafka.common.serialization.StringSerializer
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- url: jdbc:mysql://192.168.200.130:3306/leadnews_admin?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
- username: root
- password: root
- # 设置Mapper接口所对应的XML文件位置,如果你在Mapper接口中有自定义方法,需要进行该配置
- mybatis-plus:
- mapper-locations: classpath*:mapper/*.xml
- # 设置别名包扫描路径,通过该属性可以给包中的类注册别名
- type-aliases-package: com.heima.model.admin.pojos
- minio:
- accessKey: minio
- secretKey: minio123
- bucket: leadnews
- endpoint: http://192.168.200.130:9000
- readPath: http://192.168.200.130:9000
- feign:
- # 开启feign对hystrix熔断降级的支持
- hystrix:
- enabled: true
- # 修改调用超时时间
- client:
- config:
- default:
- connectTimeout: 5000
- readTimeout: 5000
- package com.heima.admin.config;
-
- import com.heima.admin.interceptor.AdTokenInterceptor;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
- /**
- * @author Z-熙玉
- * @version 1.0
- */
- @Configuration
- public class WebMvcConfig implements WebMvcConfigurer {
-
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- registry.addInterceptor(new AdTokenInterceptor())
- .addPathPatterns("/**");
- }
- }
- package com.heima.admin.interceptor;
-
- import com.heima.model.admin.pojos.AdUser;
- import com.heima.model.wemedia.pojos.WmUser;
- import com.heima.utils.thread.AdThreadLocalUtil;
- import com.heima.utils.thread.WmThreadLocalUtil;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.web.servlet.HandlerInterceptor;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- /**
- * @author Z-熙玉
- * @version 1.0
- */
- @Slf4j
- public class AdTokenInterceptor implements HandlerInterceptor {
-
- /**
- * 得到用户信息并且存入当前线程中
- * @param request
- * @param response
- * @param handler
- * @return
- * @throws Exception
- */
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- String userId = request.getHeader("userId");
- if (userId != null) {
- //存入到当前线程中
- AdUser adUser = new AdUser();
- adUser.setId(Integer.valueOf(userId));
- AdThreadLocalUtil.setUser(adUser);
- log.info("AdTokenInterceptor.存入AdThreadLocalUtil成功,adUserId={}",adUser.getId());
- }
- return true;
- }
-
- /**
- * 清理线程中的数据
- * @param request
- * @param response
- * @param handler
- * @param modelAndView
- * @throws Exception
- */
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
- //AdThreadLocalUtil.clear();
- }
-
- /**
- * @param request
- * @param response
- * @param handler
- * @param ex
- * @throws Exception
- */
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
- AdThreadLocalUtil.clear();;
- }
- }
- package com.heima.admin.controller.v1;
-
- import com.heima.admin.service.AdminUserService;
- import com.heima.model.admin.dtos.AdUserDto;
- import com.heima.model.common.dtos.ResponseResult;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- /**
- * @author Z-熙玉
- * @version 1.0
- */
- @RestController
- @RequestMapping("/login")
- public class LoginController {
-
- @Autowired
- private AdminUserService adminUserService;
-
- @PostMapping("/in")
- public ResponseResult login(@RequestBody AdUserDto dto) {
- return adminUserService.login(dto);
- }
- }
AdminUserServiceImpl .java
- package com.heima.admin.service.impl;
-
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.heima.admin.mapper.AdminUserMapper;
- import com.heima.admin.service.AdminUserService;
- import com.heima.model.admin.dtos.AdUserDto;
- import com.heima.model.admin.pojos.AdUser;
- import com.heima.model.common.dtos.ResponseResult;
- import com.heima.model.common.enums.AppHttpCodeEnum;
- import com.heima.utils.common.AppJwtUtil;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.stereotype.Service;
- import org.springframework.util.DigestUtils;
-
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * @author Z-熙玉
- * @version 1.0
- */
- @Service
- @Slf4j
- public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdUser> implements AdminUserService {
-
- /**
- * 管理端用户登录
- * @param dto
- * @return
- */
- @Override
- public ResponseResult login(AdUserDto dto) {
- //检查参数
- if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
- return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码为空");
- }
-
- //查询用户
- AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
- if (user == null) {
- return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户名不存在");
- }
-
- //对比密码
- String salt = user.getSalt();
- String pswd = dto.getPassword();
- pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
- if (pswd.equals(user.getPassword())) {
- //返回数据 jwt
- Map<String,Object> map = new HashMap<>();
- map.put("token", AppJwtUtil.getToken(user.getId().longValue()));
- user.setSalt("");
- user.setPassword("");
- map.put("user",user);
- return ResponseResult.okResult(map);
- } else {
- return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
- }
- }
- }
启动heima-leadnews-admin-gateway和heima-leadnews-admin进行登录测试,可以正常登录
前置说明:敏感词功能在自媒体模块中进行完善,因为前端发送的请求是以wemedia为前缀的,所以会被网关路由到自媒体模块,我也不晓得为什么这么设计,不改前端的话只能这么做了。
sensitiveDto.java
- package com.heima.model.admin.dtos;
-
- import com.heima.model.common.dtos.PageRequestDto;
- import lombok.Data;
-
- /**
- * @author Z-熙玉
- * @version 1.0
- */
- @Data
- public class SensitiveDto extends PageRequestDto {
- private String name;
- }
WmSensitive.java
- package com.heima.model.wemedia.pojos;
-
- import com.baomidou.mybatisplus.annotation.IdType;
- import com.baomidou.mybatisplus.annotation.TableField;
- import com.baomidou.mybatisplus.annotation.TableId;
- import com.baomidou.mybatisplus.annotation.TableName;
- import lombok.Data;
-
- import java.io.Serializable;
- import java.util.Date;
-
- /**
- * <p>
- * 敏感词信息表
- * </p>
- *
- * @author itheima
- */
- @Data
- @TableName("wm_sensitive")
- public class WmSensitive implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- /**
- * 主键
- */
- @TableId(value = "id", type = IdType.AUTO)
- private Integer id;
-
- /**
- * 敏感词
- */
- @TableField("sensitives")
- private String sensitives;
-
- /**
- * 创建时间
- */
- @TableField("created_time")
- private Date createdTime;
-
- }
WmSensitiveController.java
- package com.heima.wemedia.controller.v1;
-
- import com.heima.model.admin.dtos.SensitiveDto;
- import com.heima.model.admin.pojos.AdSensitive;
- import com.heima.model.common.dtos.ResponseResult;
- import com.heima.wemedia.service.WmSensitiveService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.*;
-
- /**
- * @author Z-熙玉
- * @version 1.0
- */
- @RestController
- @RequestMapping("/api/v1/sensitive")
- public class WmSensitiveController {
-
- @Autowired
- private WmSensitiveService wmSensitiveService;
-
- @PostMapping("/list")
- public ResponseResult list(@RequestBody SensitiveDto dto) {
- return wmSensitiveService.findList(dto);
- }
-
- @DeleteMapping("/del/{id}")
- public ResponseResult del(@PathVariable("id") Integer id) {
- return wmSensitiveService.delSensitive(id);
- }
-
- @PostMapping("/save")
- public ResponseResult save(@RequestBody AdSensitive adSensitive) {
- return wmSensitiveService.saveSensitive(adSensitive);
- }
-
- @PostMapping("/update")
- public ResponseResult update(@RequestBody AdSensitive adSensitive) {
- return wmSensitiveService.updateSensitive(adSensitive);
- }
- }
WmSensitiveService.java
- package com.heima.wemedia.service;
-
- import com.baomidou.mybatisplus.extension.service.IService;
- import com.heima.model.admin.dtos.SensitiveDto;
- import com.heima.model.admin.pojos.AdSensitive;
- import com.heima.model.common.dtos.ResponseResult;
- import com.heima.model.wemedia.pojos.WmSensitive;
-
- /**
- * @author Z-熙玉
- * @version 1.0
- */
- public interface WmSensitiveService extends IService<WmSensitive> {
-
- /**
- * 敏感词列表
- * @param dto
- * @return
- */
- ResponseResult findList(SensitiveDto dto);
-
- /**
- * 根据id删除敏感词信息
- * @param id
- * @return
- */
- ResponseResult delSensitive(Integer id);
-
- /**
- * 保存敏感词
- * @param adSensitive
- * @return
- */
- ResponseResult saveSensitive(AdSensitive adSensitive);
-
- /**
- * 更新敏感词信息
- * @param adSensitive
- * @return
- */
- ResponseResult updateSensitive(AdSensitive adSensitive);
- }
WmSensitiveServiceImpl.java
- package com.heima.wemedia.service.impl;
-
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.core.metadata.IPage;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.heima.model.admin.dtos.SensitiveDto;
- import com.heima.model.admin.pojos.AdSensitive;
- import com.heima.model.common.dtos.PageResponseResult;
- import com.heima.model.common.dtos.ResponseResult;
- import com.heima.model.common.enums.AppHttpCodeEnum;
- import com.heima.model.wemedia.pojos.WmChannel;
- import com.heima.model.wemedia.pojos.WmSensitive;
- import com.heima.wemedia.mapper.WmSensitiveMapper;
- import com.heima.wemedia.service.WmSensitiveService;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.beans.BeanUtils;
- import org.springframework.stereotype.Service;
-
- import java.util.Date;
-
- /**
- * @author Z-熙玉
- * @version 1.0
- */
- @Service
- @Slf4j
- public class WmSensitiveServiceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive> implements WmSensitiveService {
-
-
- /**
- * 敏感词分页条件查询
- * @param dto
- * @return
- */
- @Override
- public ResponseResult findList(SensitiveDto dto) {
- //检查参数
- dto.checkParam();
-
- //分页查询
- IPage page = new Page(dto.getPage(), dto.getSize());
- LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
-
- //按照创建时间倒序查询
- queryWrapper.orderByDesc(WmSensitive::getCreatedTime);
-
- //按照敏感词模糊查询
- if (StringUtils.isNotBlank(dto.getName())) {
- queryWrapper.like(WmSensitive::getSensitives, dto.getName());
- }
-
- page = page(page, queryWrapper);
-
- //返回结果
- ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
- responseResult.setData(page.getRecords());
- return responseResult;
- }
-
- /**
- * 根据id删除敏感词信息
- * @param id
- * @return
- */
- @Override
- public ResponseResult delSensitive(Integer id) {
-
- //校验参数
- if (id == null) {
- return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
- }
-
- //查询数据是否存在
- WmSensitive wmSensitive = getById(id);
- if (wmSensitive == null) {
- return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
- }
-
- //根据id删除
- removeById(id);
- return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
- }
-
- /**
- * 保存敏感词
- * @param adSensitive
- * @return
- */
- @Override
- public ResponseResult saveSensitive(AdSensitive adSensitive) {
-
- //参数校验
- if (adSensitive == null) {
- return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
- }
-
- //属性拷贝
- WmSensitive wmSensitive = new WmSensitive();
- BeanUtils.copyProperties(adSensitive, wmSensitive);
-
- //判断敏感词是否已经存在
- WmSensitive sensitive = getOne(Wrappers.<WmSensitive>lambdaQuery()
- .eq(WmSensitive::getSensitives, adSensitive.getSensitives()));
- if (sensitive != null) {
- return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
- }
-
- wmSensitive.setCreatedTime(new Date());
- save(wmSensitive);
- return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
- }
-
- /**
- * 更新敏感词信息
- * @param adSensitive
- * @return
- */
- @Override
- public ResponseResult updateSensitive(AdSensitive adSensitive) {
-
- //校验参数
- if (adSensitive == null) {
- return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
- }
-
- //属性拷贝
- WmSensitive wmSensitive = new WmSensitive();
- BeanUtils.copyProperties(adSensitive, wmSensitive);
-
- //修改信息
- updateById(wmSensitive);
- return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
- }
- }
启动admin和wemedia以及他们的网关,以及schedule模块进行测试。
这部分还是在自媒体模块当中完成。提醒:在频道分页查询中,在接口文档中所示,channelDto并没有status参数,也就是不能根据状态进行精确查询,小伙伴们可以自己在channelDto中加上status属性,试一下可不可以根据状态进行精确查询
channelDto
- package com.heima.model.admin.dtos;
-
- import com.heima.model.common.dtos.PageRequestDto;
- import lombok.Data;
-
- /**
- * @author Z-熙玉
- * @version 1.0
- */
- @Data
- public class ChannelDto extends PageRequestDto {
-
- /**
- * 频道名称
- */
- private String name;
- }
AdChannel
- package com.heima.model.admin.pojos;
-
- import com.heima.model.wemedia.pojos.WmChannel;
-
- /**
- * @author Z-熙玉
- * @version 1.0
- */
- public class AdChannel extends WmChannel {
- }
WmChannelController
- package com.heima.wemedia.controller.v1;
-
- import com.heima.model.admin.dtos.ChannelDto;
- import com.heima.model.admin.pojos.AdChannel;
- import com.heima.model.common.dtos.ResponseResult;
- import com.heima.wemedia.service.WmChannelService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.*;
-
- /**
- * @author Z-熙玉
- * @version 1.0
- */
- @RestController
- @RequestMapping("/api/v1/channel")
- public class WmChannelController {
-
- @Autowired
- private WmChannelService wmChannelService;
-
- @GetMapping("/channels")
- public ResponseResult findAll() {
- return wmChannelService.findAll();
- }
-
- @PostMapping("/list")
- public ResponseResult list(@RequestBody ChannelDto dto) {
- return wmChannelService.findList(dto);
- }
-
- @PostMapping("/save")
- public ResponseResult save(@RequestBody AdChannel adChannel) {
- return wmChannelService.saveChannel(adChannel);
- }
-
- @PostMapping("/update")
- public ResponseResult update(@RequestBody AdChannel adChannel) {
- return wmChannelService.updateChannel(adChannel);
- }
-
- @GetMapping("/del/{id}")
- public ResponseResult del(@PathVariable("id") Integer id) {
- return wmChannelService.deleteChannel(id);
- }
- }
WmChannelService
- package com.heima.wemedia.service;
-
- import com.baomidou.mybatisplus.extension.service.IService;
- import com.heima.model.admin.dtos.ChannelDto;
- import com.heima.model.admin.pojos.AdChannel;
- import com.heima.model.common.dtos.ResponseResult;
- import com.heima.model.wemedia.pojos.WmChannel;
-
- public interface WmChannelService extends IService<WmChannel> {
-
- /**
- * 查询所有频道
- * @return
- */
- ResponseResult findAll();
-
- /**
- * 根据条件查询频道
- * @param dto
- * @return
- */
- ResponseResult findList(ChannelDto dto);
-
- /**
- * 新增频道
- * @param adChannel
- * @return
- */
- ResponseResult saveChannel(AdChannel adChannel);
-
- /**
- * 修改频道信息
- * @param adChannel
- * @return
- */
- ResponseResult updateChannel(AdChannel adChannel);
-
- /**
- * 根据id删除频道信息
- * @param id
- * @return
- */
- ResponseResult deleteChannel(Integer id);
- }
WmChannelServiceImpl
- package com.heima.wemedia.service.impl;
-
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.core.metadata.IPage;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.heima.model.admin.dtos.ChannelDto;
- import com.heima.model.admin.pojos.AdChannel;
- import com.heima.model.common.dtos.PageResponseResult;
- import com.heima.model.common.dtos.ResponseResult;
- import com.heima.model.common.enums.AppHttpCodeEnum;
- import com.heima.model.wemedia.pojos.WmChannel;
- import com.heima.model.wemedia.pojos.WmNews;
- import com.heima.wemedia.mapper.WmChannelMapper;
- import com.heima.wemedia.mapper.WmNewsMapper;
- import com.heima.wemedia.service.WmChannelService;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.beans.BeanUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
-
- import java.util.Date;
-
- @Service
- @Transactional
- @Slf4j
- public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {
-
- /**
- * 查询所有频道
- * @return
- */
- @Override
- public ResponseResult findAll() {
- return ResponseResult.okResult(list());
- }
-
- /**
- * 频道条件分页查询
- * @param dto
- * @return
- */
- public ResponseResult findList(ChannelDto dto) {
-
- //检查参数
- dto.checkParam();
-
- //分页条件查询
- IPage page = new Page(dto.getPage(),dto.getSize());
- LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
-
- //按照时间倒序查询
- queryWrapper.orderByDesc(WmChannel::getCreatedTime);
- //根据名称模糊查询
- if (StringUtils.isNotBlank(dto.getName())) {
- queryWrapper.like(WmChannel::getName, dto.getName());
- }
- // TODO 根据状态精确查询
-
- //根据默认排序进行排序
- queryWrapper.orderByAsc(WmChannel::getOrd);
-
- page = page(page, queryWrapper);
- //返回结果
- ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
- responseResult.setData(page.getRecords());
- return responseResult;
- }
-
- /**
- * 新增频道
- * @param adChannel
- * @return
- */
- @Override
- public ResponseResult saveChannel(AdChannel adChannel) {
- //属性拷贝
- WmChannel wmChannel = new WmChannel();
- BeanUtils.copyProperties(adChannel, wmChannel);
-
- //判断名称是否重复
- LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
- queryWrapper.eq(WmChannel::getName, wmChannel.getName());
- int count = count(queryWrapper);
- if (count > 0) {
- return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"频道名称已存在");
- }
-
- //设置默认属性值
- wmChannel.setOrd(1);
- wmChannel.setCreatedTime(new Date());
- wmChannel.setIsDefault(true);
-
- //保存数据
- save(wmChannel);
- return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(),"新增频道成功");
- }
-
- @Autowired
- private WmNewsMapper wmNewsMapper;
-
- /**
- * 修改频道信息
- * @param adChannel
- * @return
- */
- @Override
- public ResponseResult updateChannel(AdChannel adChannel) {
- //属性拷贝
- WmChannel wmChannel = new WmChannel();
- BeanUtils.copyProperties(adChannel, wmChannel);
-
- //判断当前频道是否被引用
- Integer count = wmNewsMapper
- .selectCount(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getChannelId, wmChannel.getId()));
- if (count > 0) {
- return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"该频道已被引用不能禁用");
- }
-
- updateById(wmChannel);
- return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
- }
-
- /**
- * 根据id删除频道信息
- * @param id
- * @return
- */
- @Override
- public ResponseResult deleteChannel(Integer id) {
- //校验参数
- if (id == null) {
- return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
- }
-
- //判断是否被禁用
- WmChannel wmChannel = getById(id);
- if (wmChannel.getStatus()) {
- return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"频道启用中无法删除");
- }
-
- removeById(id);
- return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
- }
- }
略
用户审核和自媒体文章审核明天更新哦,这两部分内容偏多,明天准时更新哦。有什么问题,可以在评论区留言。最后可以的话,点赞加关注支持一下吧~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。