├── .gitignore ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── pkh │ │ ├── OpenApiApplication.java │ │ ├── ServletInitializer.java │ │ ├── annotation │ │ ├── DS.java │ │ ├── PkhLog.java │ │ ├── Replace.java │ │ ├── aspect │ │ │ ├── DataSourceAspect.java │ │ │ ├── PkhLogAspect.java │ │ │ └── ReplaceAspect.java │ │ └── parser │ │ │ └── ReplaceParser.java │ │ ├── bean │ │ ├── param │ │ │ ├── AdminListParam.java │ │ │ ├── BaseListParam.java │ │ │ ├── CustomerListParam.java │ │ │ ├── OrderCreateParam.java │ │ │ ├── PikaDayEditParam.java │ │ │ ├── RoleListParam.java │ │ │ ├── UserListParam.java │ │ │ └── UserParam.java │ │ ├── response │ │ │ └── PikaResponse.java │ │ └── vo │ │ │ └── UserVo.java │ │ ├── commons │ │ ├── datasource │ │ │ ├── DynamicDataSource.java │ │ │ └── DynamicDataSourceContextHolder.java │ │ ├── jwt │ │ │ ├── JWTCredentialMatcher.java │ │ │ └── JWTToken.java │ │ └── util │ │ │ └── RSAUtil.java │ │ ├── configuraton │ │ ├── BiliLikeListener.java │ │ ├── OrderListener.java │ │ ├── PikaConfiguration.java │ │ ├── RedisConfig.java │ │ ├── RedissonConfig.java │ │ ├── WebMvcConfig.java │ │ ├── datasource │ │ │ └── DataSourceConfiguration.java │ │ └── shiro │ │ │ ├── ShiroConfig.java │ │ │ └── UserRealm.java │ │ ├── controller │ │ ├── AdminController.java │ │ ├── ArticleController.java │ │ ├── CustomerController.java │ │ ├── LoginController.java │ │ ├── OrderController.java │ │ ├── PikaDayController.java │ │ ├── RoleController.java │ │ ├── UserController.java │ │ └── VipController.java │ │ ├── dao │ │ ├── mapper │ │ │ ├── AdminUserMapper.java │ │ │ ├── MyBatisBaseDao.java │ │ │ ├── RoleMapper.java │ │ │ ├── UserMapper.java │ │ │ └── UserRoleMapper.java │ │ ├── po │ │ │ ├── Customer.java │ │ │ ├── Rights.java │ │ │ ├── Role.java │ │ │ ├── User.java │ │ │ ├── UserRole.java │ │ │ ├── Vip.java │ │ │ └── admindb │ │ │ │ └── AdminUser.java │ │ └── prop │ │ │ └── PikaDayBean.java │ │ ├── enums │ │ ├── RoleEnum.java │ │ └── SexEnum.java │ │ ├── filter │ │ ├── JWTFilter.java │ │ └── LogFilter.java │ │ ├── handler │ │ └── GlobalExceptionHandler.java │ │ ├── interceptor │ │ └── LogInterceptor.java │ │ ├── learn │ │ ├── pibatis │ │ │ ├── MapperImpl.java │ │ │ ├── MapperProxyFactory.java │ │ │ ├── MyApplication.java │ │ │ ├── Select.java │ │ │ └── UserMapper.java │ │ └── proxy │ │ │ ├── Coder.java │ │ │ └── Programmer.java │ │ ├── service │ │ ├── AdminService.java │ │ ├── ArticleService.java │ │ ├── CustomerService.java │ │ ├── LoginService.java │ │ ├── RoleService.java │ │ ├── StockService.java │ │ ├── UserService.java │ │ ├── VipService.java │ │ └── impl │ │ │ ├── AdminServiceImpl.java │ │ │ ├── ArticleServiceImpl.java │ │ │ ├── LoginServiceImpl.java │ │ │ ├── RoleServiceImpl.java │ │ │ ├── StockServiceImpl.java │ │ │ ├── UserServiceImpl.java │ │ │ └── VipServiceImpl.java │ │ └── util │ │ ├── HttpUtil.java │ │ ├── JWTUtil.java │ │ ├── RSAUtil.java │ │ └── RedisUtil.java └── resources │ ├── application.properties │ ├── logback.xml │ ├── mapper │ ├── RoleMapper.xml │ ├── UserMapper.xml │ ├── UserRoleMapper.xml │ └── admindb │ │ └── AdminUserMapper.xml │ └── mybatis-configuration.xml └── test └── java └── com └── pkh ├── OpenApiApplicationTests.java ├── annotation └── parser │ └── ReplaceTest.java ├── configuraton └── PikaDayConfigurationTest.java ├── dao └── mapper │ ├── RoleMapperTest.java │ └── UserMapperTest.java ├── service └── impl │ └── UserServiceImplTest.java └── util └── HttpUtilTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | src/main/java/com/pkh/learn/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | 17 | ### IntelliJ IDEA ### 18 | .idea 19 | *.iws 20 | *.iml 21 | *.ipr 22 | 23 | ### NetBeans ### 24 | /nbproject/private/ 25 | /nbbuild/ 26 | /dist/ 27 | /nbdist/ 28 | /.nb-gradle/ 29 | build/ 30 | !**/src/main/**/build/ 31 | !**/src/test/**/build/ 32 | 33 | ### VS Code ### 34 | .vscode/ 35 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.7.7 9 | 10 | 11 | com.pkh 12 | open-api 13 | 0.0.1-SNAPSHOT 14 | war 15 | open-api 16 | open-api 17 | 18 | 8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-tomcat 30 | provided 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-test 35 | test 36 | 37 | 38 | 39 | 40 | com.alibaba 41 | fastjson 42 | 1.2.83 43 | 44 | 45 | 46 | 47 | ch.qos.logback 48 | logback-access 49 | 1.1.7 50 | 51 | 52 | ch.qos.logback 53 | logback-classic 54 | 1.1.7 55 | 56 | 57 | ch.qos.logback 58 | logback-core 59 | 1.1.7 60 | 61 | 62 | com.squareup.okhttp3 63 | okhttp 64 | 3.10.0 65 | 66 | 67 | 68 | org.projectlombok 69 | lombok 70 | 1.16.18 71 | 72 | 73 | 74 | mysql 75 | mysql-connector-java 76 | 8.0.13 77 | 78 | 79 | 80 | org.mybatis.spring.boot 81 | mybatis-spring-boot-starter 82 | 1.3.1 83 | 84 | 85 | 86 | log4j 87 | log4j 88 | 1.2.17 89 | 90 | 91 | 92 | org.aspectj 93 | aspectjrt 94 | 95 | 96 | 97 | org.aspectj 98 | aspectjweaver 99 | 100 | 101 | 102 | org.apache.httpcomponents.client5 103 | httpclient5 104 | 5.1.4 105 | 106 | 107 | 108 | 109 | org.springframework.boot 110 | spring-boot-starter-data-redis 111 | 112 | 113 | 114 | 115 | org.redisson 116 | redisson-spring-boot-starter 117 | 3.23.5 118 | 119 | 120 | 121 | 122 | org.apache.shiro 123 | shiro-spring 124 | 1.10.1 125 | 126 | 127 | 128 | 129 | com.auth0 130 | java-jwt 131 | 3.10.3 132 | 133 | 134 | 135 | 136 | 137 | 138 | org.springframework.boot 139 | spring-boot-maven-plugin 140 | 141 | 142 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/OpenApiApplication.java: -------------------------------------------------------------------------------- 1 | package com.pkh; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.context.annotation.EnableAspectJAutoProxy; 8 | 9 | @SpringBootApplication 10 | @ComponentScan("com.pkh.*") 11 | @MapperScan("com.pkh.dao.mapper") 12 | @EnableAspectJAutoProxy(proxyTargetClass = true) 13 | public class OpenApiApplication { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(OpenApiApplication.class, args); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/ServletInitializer.java: -------------------------------------------------------------------------------- 1 | package com.pkh; 2 | 3 | import org.springframework.boot.builder.SpringApplicationBuilder; 4 | import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 5 | 6 | public class ServletInitializer extends SpringBootServletInitializer { 7 | 8 | @Override 9 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 10 | return application.sources(OpenApiApplication.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/annotation/DS.java: -------------------------------------------------------------------------------- 1 | package com.pkh.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target({ElementType.METHOD,ElementType.TYPE}) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface DS { 11 | String value() default ""; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/annotation/PkhLog.java: -------------------------------------------------------------------------------- 1 | package com.pkh.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target(ElementType.METHOD) 10 | public @interface PkhLog { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/annotation/Replace.java: -------------------------------------------------------------------------------- 1 | package com.pkh.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target({ElementType.FIELD}) 10 | public @interface Replace { 11 | 12 | String source() default ""; 13 | 14 | String target() default ""; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/annotation/aspect/DataSourceAspect.java: -------------------------------------------------------------------------------- 1 | package com.pkh.annotation.aspect; 2 | 3 | import com.pkh.annotation.DS; 4 | import com.pkh.commons.datasource.DynamicDataSourceContextHolder; 5 | import org.aspectj.lang.JoinPoint; 6 | import org.aspectj.lang.annotation.After; 7 | import org.aspectj.lang.annotation.Aspect; 8 | import org.aspectj.lang.annotation.Before; 9 | import org.aspectj.lang.annotation.Pointcut; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | import org.springframework.core.annotation.Order; 13 | import org.springframework.stereotype.Component; 14 | 15 | @Aspect 16 | @Order(-10) 17 | @Component 18 | public class DataSourceAspect { 19 | /** 20 | * 日志打印工具 21 | */ 22 | private static final Logger logger = LoggerFactory.getLogger(DataSourceAspect.class); 23 | 24 | @Pointcut("@annotation(com.pkh.annotation.DS)") 25 | public void dataSourceAspect(){} 26 | 27 | @Before("dataSourceAspect() && @annotation(ds)") 28 | public void changeDataSource(JoinPoint joinPoint, DS ds) { 29 | String dsId = ds.value(); 30 | if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) { 31 | DynamicDataSourceContextHolder.setDataSourceType("pkhdb"); 32 | logger.warn("datasource not exist, dsId:{}", dsId); 33 | } else { 34 | logger.info("change dataSource to:" + ds.value() + ". method:" + joinPoint.getSignature()); 35 | DynamicDataSourceContextHolder.setDataSourceType(ds.value()); 36 | } 37 | } 38 | 39 | @After("@annotation(ds)") 40 | public void restoreDataSource(JoinPoint point, DS ds) { 41 | DynamicDataSourceContextHolder.clearDataSourceType(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/annotation/aspect/PkhLogAspect.java: -------------------------------------------------------------------------------- 1 | package com.pkh.annotation.aspect; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.aspectj.lang.JoinPoint; 6 | import org.aspectj.lang.annotation.After; 7 | import org.aspectj.lang.annotation.Aspect; 8 | import org.aspectj.lang.annotation.Before; 9 | import org.aspectj.lang.annotation.Pointcut; 10 | import org.aspectj.lang.reflect.MethodSignature; 11 | import org.springframework.stereotype.Component; 12 | import org.springframework.web.context.request.RequestContextHolder; 13 | import org.springframework.web.context.request.ServletRequestAttributes; 14 | 15 | import javax.servlet.http.HttpServletRequest; 16 | import java.text.SimpleDateFormat; 17 | import java.util.Date; 18 | 19 | @Component 20 | @Aspect 21 | @Slf4j 22 | public class PkhLogAspect { 23 | 24 | @Pointcut("@annotation(com.pkh.annotation.PkhLog)") 25 | public void pkhLogAspect(){} 26 | 27 | @Before("pkhLogAspect()") 28 | public void beforePkhLog(JoinPoint joinPoint) { 29 | ServletRequestAttributes requestAttributes = 30 | (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 31 | HttpServletRequest request = requestAttributes.getRequest(); 32 | 33 | String methodName = joinPoint.getSignature().getName(); 34 | log.info("========================================= Method " + methodName + "() begin========================================="); 35 | // 执行时间 36 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 37 | Date d= new Date(); 38 | String time = sdf.format(d); 39 | log.info("Time : " + time); 40 | // 打印请求 URL 41 | log.info("URL : " + request.getRequestURL()); 42 | // 打印 请求方法 43 | log.info("HTTP Method : " + request.getMethod()); 44 | // 打印controller 的全路径以及执行方法 45 | log.info("Class Method : " + joinPoint.getSignature().getDeclaringTypeName() + "." + methodName); 46 | // 打印请求的 IP 47 | log.info("IP : " + request.getRemoteHost()); 48 | // 打印请求入参 49 | log.info("Request Args : " + JSON.toJSONString(joinPoint.getArgs())); 50 | log.info("Executing Controller..."); 51 | } 52 | 53 | @After("pkhLogAspect()") 54 | public void afterPkhLog(JoinPoint joinPoint) { 55 | String methodName = joinPoint.getSignature().getName(); 56 | log.info("========================================= Method " + methodName + "() End ========================================="); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/annotation/aspect/ReplaceAspect.java: -------------------------------------------------------------------------------- 1 | package com.pkh.annotation.aspect; 2 | 3 | import com.pkh.annotation.Replace; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.aspectj.lang.JoinPoint; 6 | import org.aspectj.lang.annotation.Around; 7 | import org.aspectj.lang.annotation.Aspect; 8 | import org.aspectj.lang.annotation.Pointcut; 9 | import org.springframework.core.annotation.Order; 10 | import org.springframework.stereotype.Component; 11 | 12 | import java.lang.reflect.Field; 13 | 14 | @Aspect 15 | @Order(1) 16 | @Component 17 | @Slf4j 18 | public class ReplaceAspect { 19 | /** 20 | * 定义切点,@Replace为切点 21 | */ 22 | @Pointcut("@within(com.pkh.annotation.Replace)") 23 | public void replaceAspect() {} 24 | 25 | /** 26 | * 切入点之前执行 27 | */ 28 | @Around("replaceAspect()") 29 | public void parseReplace(JoinPoint joinPoint) { 30 | // System.out.println("parseReplace before"); 31 | log.info("-----------around--------------"); 32 | Object o = joinPoint.getTarget(); 33 | Class clazz = o.getClass(); 34 | try { 35 | Field[] fields = clazz.getDeclaredFields(); 36 | for (Field field : fields) { 37 | if (field.isAnnotationPresent(Replace.class)) { 38 | field.setAccessible(true); 39 | // 获取当前field设置的注解 40 | Replace trimSpace = field.getAnnotation(Replace.class); 41 | String source = trimSpace.source(); 42 | String target = trimSpace.target(); 43 | 44 | // 获取当前field的值进行处理 " kangkang@pika.com " 45 | String s = String.valueOf(field.get(o)); 46 | String replace = s.replace(target, source); 47 | field.set(o,replace); 48 | } 49 | } 50 | } catch (Exception e) { 51 | e.printStackTrace(); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/annotation/parser/ReplaceParser.java: -------------------------------------------------------------------------------- 1 | package com.pkh.annotation.parser; 2 | 3 | import com.pkh.annotation.Replace; 4 | 5 | import java.lang.reflect.Field; 6 | 7 | public class ReplaceParser { 8 | 9 | /** 10 | * 解析Replace注解 11 | * 12 | * @param o 解析对象 13 | */ 14 | public static Object parse(Object o) { 15 | Class mClass = null; 16 | Object o1 = o; 17 | try { 18 | mClass = o.getClass(); 19 | Field[] fields = mClass.getDeclaredFields(); 20 | for (Field field : fields) { 21 | if (field.isAnnotationPresent(Replace.class)) { 22 | field.setAccessible(true); 23 | // 获取当前field设置的注解 24 | Replace trimSpace = field.getAnnotation(Replace.class); 25 | String source = trimSpace.source(); 26 | String target = trimSpace.target(); 27 | 28 | // 获取当前field的值进行处理 " kangkang@pika.com " 29 | String s = String.valueOf(field.get(o1)); 30 | String replace = s.replace(target, source); 31 | field.set(o1,replace); 32 | } 33 | } 34 | } catch (Exception e) { 35 | e.printStackTrace(); 36 | } 37 | return o1; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/bean/param/AdminListParam.java: -------------------------------------------------------------------------------- 1 | package com.pkh.bean.param; 2 | 3 | public class AdminListParam extends BaseListParam { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/bean/param/BaseListParam.java: -------------------------------------------------------------------------------- 1 | package com.pkh.bean.param; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.List; 6 | 7 | @Data 8 | public class BaseListParam { 9 | // 页码 10 | private Integer pageIndex; 11 | 12 | // 页面大小 13 | private Integer pageSize; 14 | 15 | // 排序字段 16 | private String sortBy; 17 | 18 | // 顺序: 正序 倒序 19 | private String sortOrder; 20 | 21 | // 分页计算offset 22 | private Integer offset; 23 | 24 | // 语言类型 25 | private List langTypes; 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/bean/param/CustomerListParam.java: -------------------------------------------------------------------------------- 1 | package com.pkh.bean.param; 2 | 3 | public class CustomerListParam extends BaseListParam{ 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/bean/param/OrderCreateParam.java: -------------------------------------------------------------------------------- 1 | package com.pkh.bean.param; 2 | 3 | public class OrderCreateParam { 4 | private String productId; 5 | 6 | private Integer count; 7 | 8 | public String getProductId() { 9 | return productId; 10 | } 11 | 12 | public void setProductId(String productId) { 13 | this.productId = productId; 14 | } 15 | 16 | public Integer getCount() { 17 | return count; 18 | } 19 | 20 | public void setCount(Integer count) { 21 | this.count = count; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/bean/param/PikaDayEditParam.java: -------------------------------------------------------------------------------- 1 | package com.pkh.bean.param; 2 | 3 | public class PikaDayEditParam { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/bean/param/RoleListParam.java: -------------------------------------------------------------------------------- 1 | package com.pkh.bean.param; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.List; 6 | 7 | @Data 8 | public class RoleListParam extends BaseListParam { 9 | /** 10 | * 角色NO 11 | */ 12 | private String roleNo; 13 | 14 | /** 15 | * 角色名称 16 | */ 17 | private String name; 18 | 19 | /** 20 | * 状态 0:初始 1:激活 2:失效 21 | */ 22 | private String status; 23 | 24 | /** 25 | * 类型 26 | */ 27 | private String type; 28 | 29 | private List createTime; 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/bean/param/UserListParam.java: -------------------------------------------------------------------------------- 1 | package com.pkh.bean.param; 2 | 3 | import com.pkh.annotation.Replace; 4 | import lombok.Data; 5 | 6 | import java.util.List; 7 | 8 | @Data 9 | public class UserListParam extends BaseListParam{ 10 | 11 | @Replace(source = "_", target = " ") 12 | private String userId; 13 | 14 | private String sex; 15 | 16 | private List createTime; 17 | 18 | public UserListParam() { 19 | } 20 | 21 | public UserListParam(String userId) { 22 | this.userId = userId; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/bean/param/UserParam.java: -------------------------------------------------------------------------------- 1 | package com.pkh.bean.param; 2 | 3 | import com.pkh.annotation.Replace; 4 | import lombok.Data; 5 | 6 | import java.util.List; 7 | 8 | @Data 9 | public class UserParam extends BaseListParam{ 10 | 11 | private String userId; 12 | 13 | private String password; 14 | 15 | public UserParam(String userId, String password) { 16 | this.userId = userId; 17 | this.password = password; 18 | } 19 | 20 | public String getUserId() { 21 | return userId; 22 | } 23 | 24 | public void setUserId(String userId) { 25 | this.userId = userId; 26 | } 27 | 28 | public String getPassword() { 29 | return password; 30 | } 31 | 32 | public void setPassword(String password) { 33 | this.password = password; 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/bean/response/PikaResponse.java: -------------------------------------------------------------------------------- 1 | package com.pkh.bean.response; 2 | 3 | import java.io.Serializable; 4 | 5 | public class PikaResponse implements Serializable { 6 | private static final long serialVersionUID = 1L; 7 | private T data; 8 | private String message; 9 | private String code; 10 | 11 | public PikaResponse() { 12 | this.code = "0"; 13 | } 14 | 15 | public PikaResponse(T data) { 16 | if (data == null) { 17 | this.code = "0"; 18 | } else { 19 | this.code = "0"; 20 | this.data = data; 21 | } 22 | this.message = "success"; 23 | } 24 | 25 | public PikaResponse(String code, String message) { 26 | this.code = code; 27 | this.message = message; 28 | } 29 | 30 | public T getData() { 31 | return data; 32 | } 33 | 34 | public void setData(T data) { 35 | this.data = data; 36 | } 37 | 38 | public String getMessage() { 39 | return message; 40 | } 41 | 42 | public void setMessage(String message) { 43 | this.message = message; 44 | } 45 | 46 | public String getCode() { 47 | return code; 48 | } 49 | 50 | public void setCode(String code) { 51 | this.code = code; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/bean/vo/UserVo.java: -------------------------------------------------------------------------------- 1 | package com.pkh.bean.vo; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | @Data 8 | public class UserVo { 9 | private Long id; 10 | 11 | private String userId; 12 | 13 | private String userName; 14 | 15 | private String sex; 16 | 17 | private String type; 18 | 19 | private String phone; 20 | 21 | private String mobie; 22 | 23 | private String email; 24 | 25 | private String weChat; 26 | 27 | private String telegram; 28 | 29 | private String address; 30 | 31 | private String zipCode; 32 | 33 | private String createTime; 34 | 35 | private String updateTime; 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/commons/datasource/DynamicDataSource.java: -------------------------------------------------------------------------------- 1 | package com.pkh.commons.datasource; 2 | 3 | import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 4 | 5 | public class DynamicDataSource extends AbstractRoutingDataSource { 6 | /** 7 | * 取得一个字符串 8 | */ 9 | @Override 10 | protected Object determineCurrentLookupKey() { 11 | return DynamicDataSourceContextHolder.getDataSourceType(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/commons/datasource/DynamicDataSourceContextHolder.java: -------------------------------------------------------------------------------- 1 | package com.pkh.commons.datasource; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class DynamicDataSourceContextHolder { 7 | /** 8 | * 使用ThreadLocal维护变量 9 | */ 10 | private static final ThreadLocal contextHolder = new ThreadLocal<>(); 11 | 12 | /** 13 | * 管理所有的数据源id 14 | */ 15 | public static List dataSourceIds = new ArrayList<>(); 16 | 17 | /** 18 | * 设置当前数据源类型 19 | */ 20 | public static void setDataSourceType(String dataSourceType) { 21 | contextHolder.set(dataSourceType); 22 | } 23 | 24 | public static String getDataSourceType() { 25 | return contextHolder.get(); 26 | } 27 | 28 | public static void clearDataSourceType() { 29 | contextHolder.remove(); 30 | } 31 | 32 | /** 33 | * 判断指定DataSource当前是否存在 34 | * 35 | * @param dataSourceId 数据源Id 36 | * @return 37 | */ 38 | public static boolean containsDataSource(String dataSourceId) { 39 | return dataSourceIds.contains(dataSourceId); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/commons/jwt/JWTCredentialMatcher.java: -------------------------------------------------------------------------------- 1 | package com.pkh.commons.jwt; 2 | 3 | import com.auth0.jwt.exceptions.TokenExpiredException; 4 | import com.pkh.dao.po.User; 5 | import org.apache.shiro.authc.AuthenticationInfo; 6 | import org.apache.shiro.authc.AuthenticationToken; 7 | import org.apache.shiro.authc.credential.HashedCredentialsMatcher; 8 | 9 | import java.security.MessageDigest; 10 | import java.security.NoSuchAlgorithmException; 11 | 12 | public class JWTCredentialMatcher extends HashedCredentialsMatcher { 13 | 14 | private static final String HEXITS = "0123456789abcdef"; 15 | @Override 16 | public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo info) { 17 | String token = String.valueOf(authenticationToken.getCredentials()); 18 | User user =(User) info.getPrincipals().getPrimaryPrincipal(); 19 | try { 20 | // return JWTUtil.verify(token, user.getUserName(), user.getPassword()); 21 | return true; 22 | } catch (TokenExpiredException e) { 23 | 24 | throw new RuntimeException("token过期"); 25 | } 26 | } 27 | /** 28 | * 检查用户输入的密码,加密后是否和数据库存储的密码一致 29 | * 1. 截取随机密码 30 | * 2. 根据随机密码生成sha1摘要 31 | * 3. 根据sha1摘要和模式串生成乱码密钥 32 | * 4. 对比新生成的乱码密钥和数据库中存储的乱码密钥是否一致 33 | * 34 | * sha1$raYr1$da39a3ee5e6b4b0d3255bfef95601890afd80709 35 | * 36 | * @param password 密码 37 | * @param encryptPassword 存储的加密后的密码 38 | * @return 39 | * @throws Exception 40 | */ 41 | public static boolean checkPassword(String password, String encryptPassword) throws Exception { 42 | String[] pwdList = encryptPassword.split("\\$"); 43 | if (pwdList.length == 3) { 44 | if (pwdList[0].equals("sha1")) { 45 | MessageDigest sha1 = createSha1(pwdList[1] + password); 46 | String pwdHash = getPwdHash(sha1, HEXITS); 47 | if (pwdList[2].equals(pwdHash)) { 48 | return true; 49 | } 50 | } 51 | } 52 | return false; 53 | } 54 | 55 | 56 | /** 57 | * 对明文密码进行加密 58 | * 1. 密码+随机数组成随机字符串 59 | * 2. 对随机字符串生成sha1摘要 60 | * 3. 根据sha1摘要和模式串生成乱码密钥 61 | * 62 | * 加密后密码样例:sha1$raYr1$da39a3ee5e6b4b0d3255bfef95601890afd80709 63 | * 64 | * @param password 明文密码 65 | * @return 66 | * @throws Exception 67 | */ 68 | // public static String encryptPassword(String password) throws Exception { 69 | // String random = SysTool.getRandomString(5); 70 | // String value = random + password; 71 | // MessageDigest sha1 = createSha1(value); 72 | // String pwdHash = getPwdHash(sha1, HEXITS); 73 | // return "sha1$" + random + "$" + pwdHash; 74 | // } 75 | 76 | /** 77 | * 根据明文密码生成sha1摘要 78 | * 79 | * @param value 明文密码 80 | * @return 81 | * @throws NoSuchAlgorithmException 82 | */ 83 | private static MessageDigest createSha1(String value) throws NoSuchAlgorithmException { 84 | MessageDigest sha1 = MessageDigest.getInstance("sha1"); 85 | sha1.reset(); 86 | sha1.update(value.getBytes()); 87 | return sha1; 88 | } 89 | 90 | /** 91 | * 根据sha1摘要 和 模式串生成密码 92 | * 93 | * @param sha1 94 | * @param hexits 95 | * @return 96 | */ 97 | private static String getPwdHash(MessageDigest sha1, String hexits) { 98 | byte[] pwd = sha1.digest(); 99 | StringBuilder sb = new StringBuilder(); 100 | for (byte b : pwd) { 101 | sb.append(hexits.charAt((b >>> 4) & 0xf)); 102 | sb.append(hexits.charAt(b & 0xf)); 103 | } 104 | return sb.toString(); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/commons/jwt/JWTToken.java: -------------------------------------------------------------------------------- 1 | package com.pkh.commons.jwt; 2 | 3 | import org.apache.shiro.authc.AuthenticationToken; 4 | 5 | public class JWTToken implements AuthenticationToken { 6 | private String token; 7 | 8 | public JWTToken(String token) { 9 | this.token = token; 10 | } 11 | 12 | public String getToken() { 13 | return token; 14 | } 15 | 16 | @Override 17 | public Object getPrincipal() { 18 | return token; 19 | } 20 | 21 | @Override 22 | public Object getCredentials() { 23 | return token; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/commons/util/RSAUtil.java: -------------------------------------------------------------------------------- 1 | package com.pkh.commons.util; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import org.apache.tomcat.util.codec.binary.Base64; 5 | 6 | import javax.crypto.Cipher; 7 | import java.security.KeyFactory; 8 | import java.security.interfaces.RSAPrivateKey; 9 | import java.security.interfaces.RSAPublicKey; 10 | import java.security.spec.PKCS8EncodedKeySpec; 11 | import java.security.spec.X509EncodedKeySpec; 12 | 13 | public class RSAUtil { 14 | private static JSONObject keyMap=new JSONObject(); 15 | 16 | static { 17 | keyMap.put("ANTPOOL_PUBLIC_KEY","MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk+89V7vpOj1rG6bTAKYM56qmFLwNCBVDJ3MltVVtxVUUByqc5b6u909MmmrLBqS//PWC6zc3wZzU1+ayh8xbUAEZuA3EjlPHIaFIVIz04RaW10+1xnby/RQE23tDqsv9a2jv/axjE/27b62nzvCWeItu1kNQ3MGdcuqKjke+LKhQ7nWPRCOd/ffVqSuRvG0YfUEkOz/6UpsPr6vrI331hWRB4DlYy8qFUmDsyvvExe4NjZWblXCqkEXRRAhi2SQRCl3teGuIHtDUxCskRIDiaMD+Qt2Yp+Vvbz6hUiqIWSIH1BoHJer/JOq2/O6X3cmuppU4AdVNgy8Bq236iXvrMQIDAQAB"); 18 | } 19 | 20 | private static String getPublicKey(String keyName) { 21 | return keyMap.getString(keyName); 22 | } 23 | 24 | /** 25 | * RSA公钥加密 26 | * 27 | * @param str 加密字符串 28 | * @param publicKeyName 公钥名称 29 | * @return 密文 30 | * @throws Exception 加密过程中的异常信息 31 | */ 32 | public static String encrypt(String str, String publicKeyName) throws Exception { 33 | String publicKey= getPublicKey(publicKeyName); 34 | //base64编码的公钥 35 | byte[] decoded = Base64.decodeBase64(publicKey); 36 | RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded)); 37 | 38 | //RSA加密 39 | Cipher cipher = Cipher.getInstance("RSA"); 40 | cipher.init(Cipher.ENCRYPT_MODE, pubKey); 41 | byte[] codeByte=cipher.doFinal(str.getBytes("UTF-8")); 42 | String outStr = Base64.encodeBase64String(codeByte); 43 | return outStr; 44 | } 45 | 46 | /** 47 | * RSA私钥解密 48 | * 49 | * @param str 加密字符串 50 | * @param privateKeyName 私钥名称 51 | * @return 铭文 52 | * @throws Exception 解密过程中的异常信息 53 | */ 54 | public static String decrypt(String str, String privateKeyName) throws Exception { 55 | //64位解码加密后的字符串 56 | byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8")); 57 | //base64编码的私钥 58 | byte[] decoded = Base64.decodeBase64(privateKeyName); 59 | RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); 60 | //RSA解密 61 | Cipher cipher = Cipher.getInstance("RSA"); 62 | cipher.init(Cipher.DECRYPT_MODE, priKey); 63 | String outStr = new String(cipher.doFinal(inputByte)); 64 | return outStr; 65 | } 66 | } 67 | 68 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/configuraton/BiliLikeListener.java: -------------------------------------------------------------------------------- 1 | package com.pkh.configuraton; 2 | 3 | import org.springframework.data.redis.connection.Message; 4 | import org.springframework.data.redis.connection.MessageListener; 5 | 6 | public class BiliLikeListener implements MessageListener { 7 | @Override 8 | public void onMessage(Message message, byte[] pattern) { 9 | String msg = message.toString(); 10 | String channel = new String(message.getChannel()); 11 | System.out.println("channel: " + channel + " msg: " + msg); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/configuraton/OrderListener.java: -------------------------------------------------------------------------------- 1 | package com.pkh.configuraton; 2 | 3 | import org.springframework.data.redis.connection.Message; 4 | import org.springframework.data.redis.connection.MessageListener; 5 | 6 | public class OrderListener implements MessageListener { 7 | @Override 8 | public void onMessage(Message message, byte[] pattern) { 9 | String msg = message.toString(); 10 | String channel = new String(message.getChannel()); 11 | System.out.println("msg: " + msg + "channel: " + channel); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/configuraton/PikaConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.pkh.configuraton; 2 | 3 | import com.pkh.dao.prop.PikaDayBean; 4 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | @Configuration 10 | @EnableAutoConfiguration 11 | public class PikaConfiguration { 12 | 13 | @Bean 14 | @ConfigurationProperties("pikaday") 15 | public PikaDayBean getPikaDayBean() { 16 | 17 | PikaDayBean pikaDayBean = new PikaDayBean(); 18 | return pikaDayBean; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/configuraton/RedisConfig.java: -------------------------------------------------------------------------------- 1 | package com.pkh.configuraton; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.beans.factory.annotation.Qualifier; 5 | import org.springframework.cache.annotation.CachingConfigurerSupport; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.data.redis.connection.MessageListener; 9 | import org.springframework.data.redis.connection.RedisConnectionFactory; 10 | import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; 11 | import org.springframework.data.redis.core.RedisTemplate; 12 | import org.springframework.data.redis.listener.ChannelTopic; 13 | import org.springframework.data.redis.listener.RedisMessageListenerContainer; 14 | import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; 15 | import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 16 | import org.springframework.data.redis.serializer.StringRedisSerializer; 17 | 18 | @Configuration 19 | @Slf4j 20 | public class RedisConfig extends CachingConfigurerSupport { 21 | 22 | /** 23 | * @param redisConnectionFactory redis连接工厂 24 | * @return 25 | */ 26 | @Bean 27 | public RedisTemplate redisTemplate( RedisConnectionFactory redisConnectionFactory) { 28 | RedisTemplate redisTemplate = new RedisTemplate<>(); 29 | // 设置Redis连接工厂 30 | redisTemplate.setConnectionFactory(redisConnectionFactory); 31 | 32 | // 设置key的序列化策略 33 | redisTemplate.setKeySerializer(new StringRedisSerializer()); 34 | 35 | // 设置value的序列化策略 36 | redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class)); 37 | 38 | return redisTemplate; 39 | } 40 | 41 | /** 42 | * 配置连接工厂 43 | * 44 | * @return 45 | */ 46 | @Bean 47 | public LettuceConnectionFactory lettuceConnectionFactory() { 48 | // 这里您可以自定义配置,或者简单地返回一个新的实例让 Spring Boot 自动填充配置 49 | return new LettuceConnectionFactory(); 50 | } 51 | 52 | @Bean 53 | public MessageListenerAdapter biliLikeListenerAdapter() { 54 | return new MessageListenerAdapter(new BiliLikeListener()); 55 | } 56 | 57 | @Bean 58 | public MessageListenerAdapter orderListenerAdapter() { 59 | return new MessageListenerAdapter(new OrderListener()); 60 | } 61 | 62 | @Bean 63 | public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory, 64 | @Qualifier("biliLikeListenerAdapter") MessageListenerAdapter biliLikeListenerAdapter, 65 | @Qualifier("orderListenerAdapter") MessageListenerAdapter orderListenerAdapter) { 66 | RedisMessageListenerContainer container = new RedisMessageListenerContainer(); 67 | container.setConnectionFactory(redisConnectionFactory); 68 | container.addMessageListener(biliLikeListenerAdapter, new ChannelTopic("__bili_like__")); 69 | container.addMessageListener(orderListenerAdapter, new ChannelTopic("__order__")); 70 | return container; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/configuraton/RedissonConfig.java: -------------------------------------------------------------------------------- 1 | package com.pkh.configuraton; 2 | 3 | import org.redisson.Redisson; 4 | import org.redisson.api.RedissonClient; 5 | import org.redisson.config.Config; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | @Configuration 10 | public class RedissonConfig { 11 | 12 | @Bean 13 | public RedissonClient redissonClient() { 14 | Config config = new Config(); 15 | // config.useClusterServers() 16 | // .addNodeAddress("redis://127.0.0.1:7001") 17 | // .addNodeAddress("redis://127.0.0.1:7002") 18 | // .addNodeAddress("redis://127.0.0.1:7003"); 19 | config.useSingleServer() 20 | .setAddress("redis://127.0.0.1:6379") 21 | .setDatabase(1); 22 | return Redisson.create(config); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/configuraton/WebMvcConfig.java: -------------------------------------------------------------------------------- 1 | package com.pkh.configuraton; 2 | 3 | import com.pkh.interceptor.LogInterceptor; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 6 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 7 | 8 | 9 | @Configuration 10 | public class WebMvcConfig implements WebMvcConfigurer { 11 | @Override 12 | public void addInterceptors(InterceptorRegistry registry) { 13 | LogInterceptor logInterceptor = new LogInterceptor(); 14 | // registry.addInterceptor(logInterceptor) 15 | // .addPathPatterns("/**"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/configuraton/datasource/DataSourceConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.pkh.configuraton.datasource; 2 | 3 | import com.pkh.commons.datasource.DynamicDataSource; 4 | import com.pkh.commons.datasource.DynamicDataSourceContextHolder; 5 | import com.zaxxer.hikari.HikariConfig; 6 | import com.zaxxer.hikari.HikariDataSource; 7 | import org.springframework.boot.context.properties.ConfigurationProperties; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | import javax.sql.DataSource; 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | 15 | @Configuration 16 | public class DataSourceConfiguration { 17 | @Bean 18 | @ConfigurationProperties(prefix = "pkhdb.datasource") 19 | public HikariConfig pkhdbConfig() { 20 | return new HikariConfig(); 21 | } 22 | 23 | @Bean 24 | @ConfigurationProperties(prefix = "admin.datasource") 25 | public HikariConfig admindbConfig() { 26 | return new HikariConfig(); 27 | } 28 | 29 | @Bean("dataSource") 30 | public DataSource dataSource() { 31 | // 将多数据源存储在Map中 32 | Map dataSourceMap = new HashMap<>(); 33 | DataSource pkhDs = new HikariDataSource(pkhdbConfig()); 34 | DataSource adminDs = new HikariDataSource(admindbConfig()); 35 | dataSourceMap.put("pkhdb", pkhDs); 36 | dataSourceMap.put("admin", adminDs); 37 | 38 | // 设置动态数据源 39 | DynamicDataSource dataSource = new DynamicDataSource(); 40 | dataSource.setTargetDataSources(dataSourceMap); 41 | 42 | // 记录多数据源ID 43 | DynamicDataSourceContextHolder.dataSourceIds.add("pkhdb"); 44 | DynamicDataSourceContextHolder.dataSourceIds.add("admin"); 45 | 46 | //设置默认的数据源 47 | dataSource.setDefaultTargetDataSource(pkhDs); 48 | return dataSource; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/configuraton/shiro/ShiroConfig.java: -------------------------------------------------------------------------------- 1 | package com.pkh.configuraton.shiro; 2 | 3 | import com.pkh.filter.JWTFilter; 4 | import org.apache.shiro.spring.web.ShiroFilterFactoryBean; 5 | import org.apache.shiro.web.mgt.DefaultWebSecurityManager; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | import javax.servlet.Filter; 10 | import java.util.HashMap; 11 | import java.util.LinkedHashMap; 12 | import java.util.Map; 13 | 14 | @Configuration 15 | public class ShiroConfig { 16 | @Bean 17 | public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager){ 18 | ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); 19 | 20 | //设置安全管理器 21 | shiroFilterFactoryBean.setSecurityManager(securityManager); 22 | 23 | Map filterMap = new HashMap<>(); 24 | filterMap.put("jwt",new JWTFilter()); 25 | shiroFilterFactoryBean.setFilters(filterMap); 26 | 27 | // Shiro内置过滤器 28 | // anon: 无需认证(登录)可以访问 authc: 必须认证才可以访问 29 | // perms: 该资源必须得到资源权限才可以访问 role: 该资源必须得到角色权限才可以访问 30 | // user: 如果使用rememberMe的功能可以直接访问 31 | Map filterChainDefinitionMap = new LinkedHashMap<>(); 32 | filterChainDefinitionMap.put("/identity/login","anon"); 33 | filterChainDefinitionMap.put("/websocket/**","anon"); 34 | filterChainDefinitionMap.put("/master/predictPerson","anon"); 35 | filterChainDefinitionMap.put("/**", "jwt"); 36 | shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); 37 | //要求登录时的链接,非必须 38 | shiroFilterFactoryBean.setLoginUrl("/login"); 39 | return shiroFilterFactoryBean; 40 | } 41 | 42 | /** 43 | * 创建DefaultWebSecurityManager 44 | */ 45 | @Bean 46 | public DefaultWebSecurityManager getDefaultWebSecurityManager(UserRealm userRealm){ 47 | DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); 48 | securityManager.setRealm(userRealm); 49 | return securityManager; 50 | } 51 | /** 52 | * 创建Realm 53 | */ 54 | @Bean 55 | public UserRealm getRealm(){ 56 | return new UserRealm(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/configuraton/shiro/UserRealm.java: -------------------------------------------------------------------------------- 1 | package com.pkh.configuraton.shiro; 2 | 3 | import com.auth0.jwt.JWT; 4 | import com.pkh.commons.jwt.JWTCredentialMatcher; 5 | import com.pkh.commons.jwt.JWTToken; 6 | import com.pkh.dao.po.User; 7 | import com.pkh.service.UserService; 8 | import com.pkh.util.RedisUtil; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.apache.shiro.authc.AuthenticationException; 11 | import org.apache.shiro.authc.AuthenticationInfo; 12 | import org.apache.shiro.authc.AuthenticationToken; 13 | import org.apache.shiro.authc.SimpleAuthenticationInfo; 14 | import org.apache.shiro.authz.AuthorizationInfo; 15 | import org.apache.shiro.realm.AuthorizingRealm; 16 | import org.apache.shiro.subject.PrincipalCollection; 17 | import org.springframework.util.ObjectUtils; 18 | 19 | import javax.annotation.Resource; 20 | 21 | @Slf4j 22 | public class UserRealm extends AuthorizingRealm { 23 | @Resource 24 | UserService userService; 25 | 26 | @Resource 27 | RedisUtil redisUtil; 28 | 29 | /** 30 | * 指定凭证匹配器,匹配器工作在认证后,授权前 31 | */ 32 | public UserRealm() { 33 | this.setCredentialsMatcher(new JWTCredentialMatcher()); 34 | } 35 | 36 | /** 37 | * 授权 38 | * 39 | * @param principalCollection 40 | * @return 41 | */ 42 | @Override 43 | protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { 44 | return null; 45 | } 46 | 47 | /** 48 | * 认证 49 | * 50 | * @param authenticationToken Shiro认证token 51 | * @return 52 | * @throws AuthenticationException 53 | */ 54 | @Override 55 | protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { 56 | // 验证jwt缓存是否命中,即token是否失效 57 | JWTToken jwtToken = (JWTToken)authenticationToken; 58 | String token = jwtToken.getToken(); 59 | if (ObjectUtils.isEmpty(redisUtil.get(token))) { 60 | return null; 61 | } 62 | // 解析token,账号是否存在,账号是否被锁定 63 | String username = JWT.decode(token).getClaim("username").asString(); 64 | User user = userService.getByUserId(username); 65 | if (ObjectUtils.isEmpty(user)) { 66 | return null; 67 | } 68 | 69 | //将用户名和密码发送要密码匹配器中 70 | SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, token,"userRealm"); 71 | return authenticationInfo; 72 | } 73 | 74 | /** 75 | * 判断token是否为JWTToken,必须重写 76 | * 77 | * @param token 78 | * @return 79 | */ 80 | @Override 81 | public boolean supports(AuthenticationToken token) { 82 | return token instanceof JWTToken; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/controller/AdminController.java: -------------------------------------------------------------------------------- 1 | package com.pkh.controller; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import com.pkh.annotation.DS; 5 | import com.pkh.bean.param.AdminListParam; 6 | import com.pkh.bean.response.PikaResponse; 7 | import com.pkh.dao.po.admindb.AdminUser; 8 | import com.pkh.service.AdminService; 9 | import com.pkh.util.RedisUtil; 10 | import lombok.extern.slf4j.Slf4j; 11 | import org.springframework.web.bind.annotation.PostMapping; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.RestController; 14 | 15 | import javax.annotation.Resource; 16 | import java.util.List; 17 | 18 | @Slf4j 19 | @RequestMapping("/admin") 20 | @RestController 21 | public class AdminController { 22 | @Resource 23 | AdminService adminService; 24 | 25 | @PostMapping("/list") 26 | @DS("admin") 27 | public PikaResponse list(AdminListParam param) { 28 | try { 29 | Integer total = adminService.countByParam(param); 30 | log.info("/admin/list, count number: {}", total); 31 | List adminList = null; 32 | if (total > 0) { 33 | adminList = adminService.getByParam(param); 34 | } 35 | JSONObject jsonObject = new JSONObject(); 36 | jsonObject.put("total", total); 37 | jsonObject.put("list", adminList); 38 | return new PikaResponse(jsonObject); 39 | } catch (Exception e) { 40 | log.info("/admin/list, failed! exception:{} ", e.getMessage()); 41 | return new PikaResponse("1", e.getMessage()); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/controller/ArticleController.java: -------------------------------------------------------------------------------- 1 | package com.pkh.controller; 2 | 3 | import com.pkh.bean.response.PikaResponse; 4 | import com.pkh.service.ArticleService; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.web.bind.annotation.PostMapping; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | import javax.annotation.Resource; 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | 14 | @Slf4j 15 | @RequestMapping("/article") 16 | @RestController 17 | public class ArticleController { 18 | 19 | @Resource 20 | ArticleService articleService; 21 | 22 | @PostMapping("/readArticle") 23 | public PikaResponse readArticle() { 24 | Long articleReadCount = articleService.readArticle("1001"); 25 | Map res = new HashMap<>(); 26 | if (articleReadCount > 0) { 27 | res.put("count", articleReadCount); 28 | } else { 29 | res.put("count", -1); 30 | } 31 | return new PikaResponse<>(res); 32 | } 33 | 34 | @PostMapping("/collectArticle") 35 | public PikaResponse collectArticle(String articleId, String userId) { 36 | Long articleCollectCount = articleService.collectArticle(articleId, userId); 37 | Map res = new HashMap<>(); 38 | if (articleCollectCount > 0) { 39 | res.put("count", articleCollectCount); 40 | } else { 41 | res.put("count", -1); 42 | } 43 | return new PikaResponse<>(res); 44 | } 45 | 46 | @PostMapping("/cancelCollectArticle") 47 | public PikaResponse cancelCollectArticle(String articleId, String userId) { 48 | Long cancelRes = articleService.cancelCollectArticle(articleId, userId); 49 | String msg = "success"; 50 | if (cancelRes < 0) { 51 | msg = "failed"; 52 | } 53 | return new PikaResponse<>(String.valueOf(cancelRes), msg); 54 | } 55 | 56 | @PostMapping("/getArticleCollectCount") 57 | public PikaResponse getArticleCollectCount(String articleId) { 58 | Long articleCollectCount = articleService.getArticleCollectCount(articleId); 59 | Map res = new HashMap<>(); 60 | res.put("count", articleCollectCount); 61 | return new PikaResponse<>(res); 62 | } 63 | 64 | @PostMapping("/likeArticle") 65 | public PikaResponse likeArticle(String articleId, String userId) { 66 | Long articleLikeCount = articleService.likeArticle(articleId, userId); 67 | Map res = new HashMap<>(); 68 | if (articleLikeCount > 0) { 69 | res.put("count", articleLikeCount); 70 | } else { 71 | res.put("count", -1); 72 | } 73 | return new PikaResponse<>(res); 74 | } 75 | 76 | @PostMapping("/getArticleLikeCount") 77 | public PikaResponse getArticleLikeCount(String articleId) { 78 | Long articleLikeCount = articleService.getArticleLikeCount(articleId); 79 | Map res = new HashMap<>(); 80 | res.put("count", articleLikeCount); 81 | return new PikaResponse<>(res); 82 | } 83 | 84 | 85 | } 86 | 87 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/controller/CustomerController.java: -------------------------------------------------------------------------------- 1 | package com.pkh.controller; 2 | 3 | import com.alibaba.fastjson.JSONArray; 4 | import com.alibaba.fastjson.JSONObject; 5 | import com.pkh.bean.param.CustomerListParam; 6 | import com.pkh.bean.response.PikaResponse; 7 | import com.pkh.dao.po.Customer; 8 | import com.pkh.service.CustomerService; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import javax.annotation.Resource; 15 | import java.util.List; 16 | 17 | @RequestMapping("/customer") 18 | @Slf4j 19 | //@RestController 20 | public class CustomerController { 21 | 22 | @Resource 23 | CustomerService customerService; 24 | 25 | @PostMapping("/list") 26 | public PikaResponse list(CustomerListParam param) { 27 | log.info("/customer/list, list param: {}", param); 28 | try { 29 | Integer total = customerService.countByParam(param); 30 | log.info("/customer/list, count number: {}", total); 31 | List customerList = customerService.getByParam(param); 32 | if (total > 0) { 33 | customerList = customerService.getByParam(param); 34 | } 35 | JSONObject jsonObject = new JSONObject(); 36 | jsonObject.put("total", total); 37 | jsonObject.put("list", customerList); 38 | return new PikaResponse(jsonObject); 39 | } catch (Exception e) { 40 | log.info("/customer/list, failed! exception:{} ", e.getMessage()); 41 | return new PikaResponse("1", e.getMessage()); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.pkh.controller; 2 | 3 | import com.pkh.bean.param.UserListParam; 4 | import com.pkh.bean.param.UserParam; 5 | import com.pkh.bean.response.PikaResponse; 6 | import com.pkh.dao.po.User; 7 | import com.pkh.service.LoginService; 8 | import com.pkh.service.UserService; 9 | import com.pkh.util.RedisUtil; 10 | import org.springframework.util.ObjectUtils; 11 | import org.springframework.util.StringUtils; 12 | import org.springframework.web.bind.annotation.RequestBody; 13 | import org.springframework.web.bind.annotation.RequestMapping; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | import javax.annotation.Resource; 17 | 18 | @RestController 19 | public class LoginController { 20 | 21 | @Resource 22 | UserService userService; 23 | 24 | @Resource 25 | LoginService loginService; 26 | 27 | @Resource 28 | RedisUtil redisUtil; 29 | 30 | @RequestMapping("/identity/login") 31 | public PikaResponse login (@RequestBody UserParam userParam) { 32 | if (ObjectUtils.isEmpty(userParam.getUserId()) || ObjectUtils.isEmpty(userParam.getPassword())) { 33 | return new PikaResponse<>("-1", "账号或密码为空"); 34 | } 35 | 36 | User user = userService.getByUserId(userParam.getUserId()); 37 | if(ObjectUtils.isEmpty(user)){ 38 | return new PikaResponse<>("-1","账号不存在!"); 39 | } 40 | 41 | String token = loginService.login(userParam.getUserId(), userParam.getPassword()); 42 | if (StringUtils.hasLength(token)) { 43 | redisUtil.set(token, user.getUserId(), 10000L); 44 | return new PikaResponse<>(token); 45 | } 46 | return new PikaResponse<>("-1", "登录失败,系统异常"); 47 | } 48 | 49 | private String generateToken(UserListParam userListParam) { 50 | return "token"; 51 | } 52 | 53 | private boolean validateUser(User user) { 54 | // 模拟用户验证逻辑 55 | // 此处省略实际的用户验证过程,假设用户名和密码均正确 56 | return true; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/controller/OrderController.java: -------------------------------------------------------------------------------- 1 | package com.pkh.controller; 2 | 3 | import com.pkh.bean.param.OrderCreateParam; 4 | import com.pkh.bean.response.PikaResponse; 5 | import com.pkh.service.StockService; 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 | import javax.annotation.Resource; 12 | 13 | @RequestMapping("/order") 14 | @RestController 15 | public class OrderController { 16 | @Resource 17 | StockService stockService; 18 | 19 | @PostMapping("/createOrder") 20 | public PikaResponse createOrder(@RequestBody OrderCreateParam param) { 21 | Boolean deductResult = stockService.deductStock(param.getProductId(), param.getCount()); 22 | if (deductResult) { 23 | // 库存扣减成功,后续操作(如创建订单等) 24 | // ... 25 | } 26 | return new PikaResponse<>("下单成功"); 27 | } 28 | 29 | @PostMapping("/createOrderSafely") 30 | public PikaResponse createOrderSafely(@RequestBody OrderCreateParam param) { 31 | Boolean haveStock = stockService.deductStockWithRedisson(param.getProductId(), param.getCount()); 32 | if (haveStock) { 33 | // 创建订单逻辑... 34 | return new PikaResponse<>("下单成功"); 35 | } else { 36 | // 库存不足,返回错误信息 37 | return new PikaResponse<>("库存扣减失败"); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/controller/PikaDayController.java: -------------------------------------------------------------------------------- 1 | package com.pkh.controller; 2 | 3 | import com.pkh.bean.param.PikaDayEditParam; 4 | import com.pkh.bean.response.PikaResponse; 5 | import com.pkh.configuraton.PikaConfiguration; 6 | import com.pkh.dao.prop.PikaDayBean; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.springframework.web.bind.annotation.PostMapping; 9 | import org.springframework.web.bind.annotation.RequestBody; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | import javax.annotation.Resource; 14 | 15 | @Slf4j 16 | @RestController 17 | @RequestMapping("/pikaDay") 18 | public class PikaDayController { 19 | 20 | @Resource 21 | PikaConfiguration pikaDayConfiguration; 22 | 23 | /** 24 | * 报名 25 | * 26 | * @param param 27 | * @return 28 | */ 29 | @PostMapping("/create") 30 | public PikaResponse create (@RequestBody PikaDayEditParam param) { 31 | PikaDayBean pikaDayBean = pikaDayConfiguration.getPikaDayBean(); 32 | long startTime = pikaDayBean.getStartTime(); 33 | long endTime = pikaDayBean.getEndTime(); 34 | long currentTime = System.currentTimeMillis(); 35 | if (currentTime < startTime || currentTime > endTime) { 36 | return new PikaResponse<>("1", "不在活动时间!"); 37 | } 38 | // 执行具体的报名逻辑 39 | return new PikaResponse<>(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/controller/RoleController.java: -------------------------------------------------------------------------------- 1 | package com.pkh.controller; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import com.pkh.bean.param.RoleListParam; 5 | import com.pkh.bean.response.PikaResponse; 6 | import com.pkh.dao.po.Role; 7 | import com.pkh.service.RoleService; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.web.bind.annotation.PostMapping; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import javax.annotation.Resource; 15 | import javax.security.auth.login.CredentialException; 16 | import java.util.ArrayList; 17 | import java.util.List; 18 | 19 | @RestController 20 | @Slf4j 21 | @RequestMapping("/role") 22 | public class RoleController { 23 | 24 | @Resource 25 | RoleService roleService; 26 | 27 | @PostMapping("/list") 28 | public PikaResponse list(@RequestBody RoleListParam param) { 29 | log.info("/role/list, param:{}", param); 30 | try { 31 | Integer total = roleService.countByParam(param); 32 | log.info("/role/list count number: {}", total); 33 | List roleList = new ArrayList<>(); 34 | if (total > 0) { 35 | roleList = roleService.getByParam(param); 36 | } 37 | JSONObject jsonObject = new JSONObject(); 38 | jsonObject.put("total", total); 39 | jsonObject.put("list", roleList); 40 | return new PikaResponse(jsonObject); 41 | } catch (Exception e) { 42 | log.info("/role/list failed, exception: {}", e.getMessage()); 43 | return new PikaResponse("-1","failed!"); 44 | } 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.pkh.controller; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import com.fasterxml.jackson.core.JsonProcessingException; 5 | import com.pkh.annotation.DS; 6 | import com.pkh.annotation.PkhLog; 7 | import com.pkh.bean.param.UserListParam; 8 | import com.pkh.bean.response.PikaResponse; 9 | import com.pkh.bean.vo.UserVo; 10 | import com.pkh.dao.po.Rights; 11 | import com.pkh.dao.po.User; 12 | import com.pkh.enums.SexEnum; 13 | import com.pkh.service.UserService; 14 | import com.pkh.util.RedisUtil; 15 | import lombok.extern.slf4j.Slf4j; 16 | import org.springframework.beans.BeanUtils; 17 | import org.springframework.util.ObjectUtils; 18 | import org.springframework.web.bind.annotation.PostMapping; 19 | import org.springframework.web.bind.annotation.RequestBody; 20 | import org.springframework.web.bind.annotation.RequestMapping; 21 | import org.springframework.web.bind.annotation.RestController; 22 | 23 | import javax.annotation.Resource; 24 | import java.util.ArrayList; 25 | import java.util.HashMap; 26 | import java.util.List; 27 | import java.util.Map; 28 | 29 | @Slf4j 30 | @RestController 31 | @RequestMapping("/user") 32 | public class UserController { 33 | 34 | @Resource 35 | UserService userService; 36 | 37 | @Resource 38 | RedisUtil redisUtil; 39 | 40 | @RequestMapping("/list") 41 | @PkhLog 42 | public PikaResponse list(UserListParam param) throws JsonProcessingException { 43 | Integer count = userService.countByParam(param); 44 | log.info("/user/list count number: {}", count); 45 | List userList = new ArrayList<>(); 46 | if (count > 0) { 47 | userList = userService.getByParam(param); 48 | } 49 | JSONObject jsonObject = new JSONObject(); 50 | jsonObject.put("total", count); 51 | jsonObject.put("list", userList); 52 | return new PikaResponse<>(jsonObject); 53 | } 54 | 55 | @PostMapping("/getByCondition") 56 | public PikaResponse getByCondition(@RequestBody UserListParam param) { 57 | log.info("/user/getByCondition param: {}", param); 58 | try { 59 | Integer count = userService.countByCondition(param); 60 | log.info("/user/getByCondition count number: {}", count); 61 | List userList = new ArrayList<>(); 62 | if (count > 0) { 63 | userList = userService.getByCondition(param); 64 | } 65 | JSONObject jsonObject = new JSONObject(); 66 | jsonObject.put("total", count); 67 | jsonObject.put("list", userList); 68 | return new PikaResponse<>(jsonObject); 69 | } catch (Exception e) { 70 | log.info("/user/getByCondition failed, exception:{}", e.getMessage()); 71 | return new PikaResponse<>("-1", "fail ed!"); 72 | } 73 | } 74 | 75 | @PostMapping("/create") 76 | public PikaResponse create(@RequestBody User param) { 77 | log.info("/user/create, param:{}", param); 78 | try { 79 | Integer count = this.countByUserId(param); 80 | if (count <= 0) { 81 | return new PikaResponse("-1","Current user already exist!" + param.getUserId()); 82 | } 83 | int res = userService.add(param); 84 | log.info("create new user, res: {}", res); 85 | if (res < 0) { 86 | return new PikaResponse("-1", "failed!"); 87 | } 88 | return new PikaResponse<>(res); 89 | } catch (Exception e) { 90 | log.info("/user/create, res:{}",e.getMessage()); 91 | return new PikaResponse("-1", "failed!"); 92 | } 93 | } 94 | 95 | /** 96 | * 根据用户Id统计个数 97 | * 98 | * @param param 参数 99 | * @return 100 | */ 101 | private Integer countByUserId(User param) { 102 | UserListParam userListParam = new UserListParam(); 103 | userListParam.setUserId(param.getUserId()); 104 | return userService.countByCondition(userListParam); 105 | } 106 | 107 | @PostMapping("/permissions") 108 | public PikaResponse permissions() { 109 | String userId = "kangkang@pika.com"; 110 | User user = userService.getByUserId(userId); 111 | if (ObjectUtils.isEmpty(user)) { 112 | return new PikaResponse<>("1", userId + " not exit"); 113 | } 114 | List rights = userService.getRights(user); 115 | JSONObject jsonObject = new JSONObject(); 116 | jsonObject.put("rights", rights); 117 | return new PikaResponse<>(jsonObject); 118 | } 119 | 120 | /** 121 | * 格式化性别 122 | * 123 | * @param user 用户 124 | * @return 125 | */ 126 | private UserVo formatSex(User user) { 127 | UserVo userVo = new UserVo(); 128 | BeanUtils.copyProperties(user, userVo); 129 | 130 | String sexStr = ""; 131 | SexEnum sexEnum = SexEnum.getByCode(Integer.valueOf(user.getSex())); 132 | if (!ObjectUtils.isEmpty(sexEnum)) { 133 | sexStr = sexEnum.getDescription(); 134 | } 135 | userVo.setSex(sexStr); 136 | return userVo; 137 | } 138 | 139 | 140 | 141 | } 142 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/controller/VipController.java: -------------------------------------------------------------------------------- 1 | package com.pkh.controller; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import com.pkh.bean.response.PikaResponse; 5 | import com.pkh.service.VipService; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | import javax.annotation.Resource; 11 | import java.util.List; 12 | 13 | @Slf4j 14 | @RestController 15 | @RequestMapping("/vip") 16 | public class VipController { 17 | 18 | @Resource 19 | VipService vipService; 20 | 21 | @RequestMapping("/list") 22 | public PikaResponse list() { 23 | try { 24 | List vipList = vipService.list(); 25 | Integer total = vipList.size(); 26 | JSONObject jsonObject = new JSONObject(); 27 | jsonObject.put("total", total); 28 | jsonObject.put("list",vipList); 29 | PikaResponse pikaResponse = new PikaResponse<>(jsonObject); 30 | return pikaResponse; 31 | } catch (Exception e) { 32 | log.info("/vip/list exception: {}",e.getMessage()); 33 | } 34 | return new PikaResponse("-1", "get list failed!"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/dao/mapper/AdminUserMapper.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.mapper; 2 | 3 | import com.pkh.dao.po.admindb.AdminUser; 4 | import org.apache.ibatis.annotations.Param; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | public interface AdminUserMapper { 10 | int deleteByPrimaryKey(Long id); 11 | 12 | int insert(AdminUser record); 13 | 14 | int insertSelective(AdminUser record); 15 | 16 | AdminUser selectByPrimaryKey(Long id); 17 | 18 | int updateByPrimaryKeySelective(AdminUser record); 19 | 20 | int updateByPrimaryKey(AdminUser record); 21 | 22 | Integer countByCondition(@Param("map")Map map); 23 | 24 | List selectByCondition(@Param("map") Map map, @Param("offset")Integer offset, @Param("pageSize") Integer pageSize); 25 | } -------------------------------------------------------------------------------- /src/main/java/com/pkh/dao/mapper/MyBatisBaseDao.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.mapper; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * DAO公共基类 7 | * @param The Model Class 这里是泛型不是Model类 8 | * @param The Primary Key Class 如果是无主键,则可以用Model来跳过,如果是多主键则是Key类 9 | */ 10 | public interface MyBatisBaseDao { 11 | int deleteByPrimaryKey(PK id); 12 | 13 | int insert(Model record); 14 | 15 | int insertSelective(Model record); 16 | 17 | Model selectByPrimaryKey(PK id); 18 | 19 | int updateByPrimaryKeySelective(Model record); 20 | 21 | int updateByPrimaryKey(Model record); 22 | } -------------------------------------------------------------------------------- /src/main/java/com/pkh/dao/mapper/RoleMapper.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.mapper; 2 | 3 | import com.pkh.bean.param.RoleListParam; 4 | import com.pkh.dao.po.Role; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | /** 10 | * RoleMapper继承基类 11 | */ 12 | public interface RoleMapper extends MyBatisBaseDao { 13 | 14 | List selectByParam(RoleListParam param); 15 | 16 | Integer countByParam(RoleListParam param); 17 | 18 | List selectByCondition(Map map); 19 | 20 | Integer countByCondition(Map map); 21 | } -------------------------------------------------------------------------------- /src/main/java/com/pkh/dao/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.mapper; 2 | 3 | import com.pkh.bean.param.UserListParam; 4 | import com.pkh.dao.po.User; 5 | import org.apache.ibatis.annotations.Param; 6 | 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | /** 11 | * UserMapper继承基类 12 | */ 13 | public interface UserMapper extends MyBatisBaseDao { 14 | 15 | List selectByParam(UserListParam param); 16 | 17 | List selectByCondition(@Param("map") Map map, @Param("offset")Integer offset, @Param("pageSize") Integer pageSize); 18 | 19 | Integer countByCondition(@Param("map")Map map); 20 | 21 | Integer countByParam(UserListParam param); 22 | 23 | } -------------------------------------------------------------------------------- /src/main/java/com/pkh/dao/mapper/UserRoleMapper.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.mapper; 2 | 3 | import com.pkh.dao.po.UserRole; 4 | 5 | /** 6 | * UserRoleMapper继承基类 7 | */ 8 | public interface UserRoleMapper extends MyBatisBaseDao { 9 | } -------------------------------------------------------------------------------- /src/main/java/com/pkh/dao/po/Customer.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.po; 2 | 3 | public class Customer { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/dao/po/Rights.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.po; 2 | 3 | public class Rights { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/dao/po/Role.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.po; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | /** 7 | * @author 8 | * 角色表 9 | */ 10 | public class Role implements Serializable { 11 | /** 12 | * 主键 13 | */ 14 | private Long id; 15 | 16 | /** 17 | * 角色NO 18 | */ 19 | private String roleNo; 20 | 21 | /** 22 | * 角色名称 23 | */ 24 | private String name; 25 | 26 | /** 27 | * 状态 0:初始 1:激活 2:失效 28 | */ 29 | private String status; 30 | 31 | /** 32 | * 类型 33 | */ 34 | private String type; 35 | 36 | /** 37 | * 创建时间 38 | */ 39 | private Date createTime; 40 | 41 | /** 42 | * 更新时间 43 | */ 44 | private Date updateTime; 45 | 46 | private static final long serialVersionUID = 1L; 47 | 48 | public Long getId() { 49 | return id; 50 | } 51 | 52 | public void setId(Long id) { 53 | this.id = id; 54 | } 55 | 56 | public String getRoleNo() { 57 | return roleNo; 58 | } 59 | 60 | public void setRoleNo(String roleNo) { 61 | this.roleNo = roleNo; 62 | } 63 | 64 | public String getName() { 65 | return name; 66 | } 67 | 68 | public void setName(String name) { 69 | this.name = name; 70 | } 71 | 72 | public String getStatus() { 73 | return status; 74 | } 75 | 76 | public void setStatus(String status) { 77 | this.status = status; 78 | } 79 | 80 | public String getType() { 81 | return type; 82 | } 83 | 84 | public void setType(String type) { 85 | this.type = type; 86 | } 87 | 88 | public Date getCreateTime() { 89 | return createTime; 90 | } 91 | 92 | public void setCreateTime(Date createTime) { 93 | this.createTime = createTime; 94 | } 95 | 96 | public Date getUpdateTime() { 97 | return updateTime; 98 | } 99 | 100 | public void setUpdateTime(Date updateTime) { 101 | this.updateTime = updateTime; 102 | } 103 | } -------------------------------------------------------------------------------- /src/main/java/com/pkh/dao/po/User.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.po; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | /** 7 | * @author 8 | * 9 | */ 10 | public class User implements Serializable { 11 | private Long id; 12 | 13 | private String userId; 14 | 15 | private String userName; 16 | 17 | private String password; 18 | 19 | private String dealPassword; 20 | 21 | private String sex; 22 | 23 | private String type; 24 | 25 | private String phone; 26 | 27 | private String mobie; 28 | 29 | private String email; 30 | 31 | private String weChat; 32 | 33 | private String telegram; 34 | 35 | private String address; 36 | 37 | private String zipCode; 38 | 39 | private Date createTime; 40 | 41 | private Date updateTime; 42 | 43 | private static final long serialVersionUID = 1L; 44 | 45 | public User(String userId) { 46 | this.userId = userId; 47 | } 48 | 49 | public Long getId() { 50 | return id; 51 | } 52 | 53 | public void setId(Long id) { 54 | this.id = id; 55 | } 56 | 57 | public String getUserId() { 58 | return userId; 59 | } 60 | 61 | public void setUserId(String userId) { 62 | this.userId = userId; 63 | } 64 | 65 | public String getUserName() { 66 | return userName; 67 | } 68 | 69 | public void setUserName(String userName) { 70 | this.userName = userName; 71 | } 72 | 73 | public String getPassword() { 74 | return password; 75 | } 76 | 77 | public void setPassword(String password) { 78 | this.password = password; 79 | } 80 | 81 | public String getDealPassword() { 82 | return dealPassword; 83 | } 84 | 85 | public void setDealPassword(String dealPassword) { 86 | this.dealPassword = dealPassword; 87 | } 88 | 89 | public String getSex() { 90 | return sex; 91 | } 92 | 93 | public void setSex(String sex) { 94 | this.sex = sex; 95 | } 96 | 97 | public String getType() { 98 | return type; 99 | } 100 | 101 | public void setType(String type) { 102 | this.type = type; 103 | } 104 | 105 | public String getPhone() { 106 | return phone; 107 | } 108 | 109 | public void setPhone(String phone) { 110 | this.phone = phone; 111 | } 112 | 113 | public String getMobie() { 114 | return mobie; 115 | } 116 | 117 | public void setMobie(String mobie) { 118 | this.mobie = mobie; 119 | } 120 | 121 | public String getEmail() { 122 | return email; 123 | } 124 | 125 | public void setEmail(String email) { 126 | this.email = email; 127 | } 128 | 129 | public String getWeChat() { 130 | return weChat; 131 | } 132 | 133 | public void setWeChat(String weChat) { 134 | this.weChat = weChat; 135 | } 136 | 137 | public String getTelegram() { 138 | return telegram; 139 | } 140 | 141 | public void setTelegram(String telegram) { 142 | this.telegram = telegram; 143 | } 144 | 145 | public String getAddress() { 146 | return address; 147 | } 148 | 149 | public void setAddress(String address) { 150 | this.address = address; 151 | } 152 | 153 | public String getZipCode() { 154 | return zipCode; 155 | } 156 | 157 | public void setZipCode(String zipCode) { 158 | this.zipCode = zipCode; 159 | } 160 | 161 | public Date getCreateTime() { 162 | return createTime; 163 | } 164 | 165 | public void setCreateTime(Date createTime) { 166 | this.createTime = createTime; 167 | } 168 | 169 | public Date getUpdateTime() { 170 | return updateTime; 171 | } 172 | 173 | public void setUpdateTime(Date updateTime) { 174 | this.updateTime = updateTime; 175 | } 176 | 177 | @Override 178 | public String toString() { 179 | return "User{" + 180 | "id=" + id + 181 | ", userId='" + userId + '\'' + 182 | ", userName='" + userName + '\'' + 183 | ", password='" + password + '\'' + 184 | ", dealPassword='" + dealPassword + '\'' + 185 | ", sex='" + sex + '\'' + 186 | ", type='" + type + '\'' + 187 | ", phone='" + phone + '\'' + 188 | ", mobie='" + mobie + '\'' + 189 | ", email='" + email + '\'' + 190 | ", weChat='" + weChat + '\'' + 191 | ", telegram='" + telegram + '\'' + 192 | ", address='" + address + '\'' + 193 | ", zipCode='" + zipCode + '\'' + 194 | ", createTime=" + createTime + 195 | ", updateTime=" + updateTime + 196 | '}'; 197 | } 198 | } -------------------------------------------------------------------------------- /src/main/java/com/pkh/dao/po/UserRole.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.po; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | /** 7 | * @author 8 | * 用户-角色表 9 | */ 10 | public class UserRole implements Serializable { 11 | /** 12 | * 主键 13 | */ 14 | private Long id; 15 | 16 | /** 17 | * 用户ID 18 | */ 19 | private String userId; 20 | 21 | /** 22 | * 角色编号 23 | */ 24 | private String roleNo; 25 | 26 | /** 27 | * 创建时间 28 | */ 29 | private Date createTime; 30 | 31 | /** 32 | * 更新时间 33 | */ 34 | private Date updateTime; 35 | 36 | private static final long serialVersionUID = 1L; 37 | 38 | public Long getId() { 39 | return id; 40 | } 41 | 42 | public void setId(Long id) { 43 | this.id = id; 44 | } 45 | 46 | public String getUserId() { 47 | return userId; 48 | } 49 | 50 | public void setUserId(String userId) { 51 | this.userId = userId; 52 | } 53 | 54 | public String getRoleNo() { 55 | return roleNo; 56 | } 57 | 58 | public void setRoleNo(String roleNo) { 59 | this.roleNo = roleNo; 60 | } 61 | 62 | public Date getCreateTime() { 63 | return createTime; 64 | } 65 | 66 | public void setCreateTime(Date createTime) { 67 | this.createTime = createTime; 68 | } 69 | 70 | public Date getUpdateTime() { 71 | return updateTime; 72 | } 73 | 74 | public void setUpdateTime(Date updateTime) { 75 | this.updateTime = updateTime; 76 | } 77 | } -------------------------------------------------------------------------------- /src/main/java/com/pkh/dao/po/Vip.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.po; 2 | 3 | public class Vip { 4 | // ID 5 | private long id; 6 | 7 | // 用户ID 8 | private String userId; 9 | 10 | // 公司 11 | private String company; 12 | 13 | // 国家编码 14 | private String countryCode; 15 | 16 | public Vip(long id, String userId, String company, String countryCode) { 17 | this.id = id; 18 | this.userId = userId; 19 | this.company = company; 20 | this.countryCode = countryCode; 21 | } 22 | 23 | public long getId() { 24 | return id; 25 | } 26 | 27 | public void setId(long id) { 28 | this.id = id; 29 | } 30 | 31 | public String getUserId() { 32 | return userId; 33 | } 34 | 35 | public void setUserId(String userId) { 36 | this.userId = userId; 37 | } 38 | 39 | public String getCompany() { 40 | return company; 41 | } 42 | 43 | public void setCompany(String company) { 44 | this.company = company; 45 | } 46 | 47 | public String getCountryCode() { 48 | return countryCode; 49 | } 50 | 51 | public void setCountryCode(String countryCode) { 52 | this.countryCode = countryCode; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/dao/po/admindb/AdminUser.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.po.admindb; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | /** 7 | * @author 8 | * 9 | */ 10 | public class AdminUser implements Serializable { 11 | private Long id; 12 | 13 | private String userId; 14 | 15 | private String userName; 16 | 17 | private String password; 18 | 19 | private String dealpassword; 20 | 21 | private String sex; 22 | 23 | private String type; 24 | 25 | private String userLevel; 26 | 27 | private String phone; 28 | 29 | private String mobile; 30 | 31 | private String email; 32 | 33 | private String weChat; 34 | 35 | private String telegram; 36 | 37 | private String address; 38 | 39 | private String zipCode; 40 | 41 | private String roleId; 42 | 43 | private String statusFlag; 44 | 45 | private String otherInfo; 46 | 47 | private Date createTime; 48 | 49 | private String langType; 50 | 51 | private String permissionLang; 52 | 53 | private static final long serialVersionUID = 1L; 54 | 55 | public Long getId() { 56 | return id; 57 | } 58 | 59 | public void setId(Long id) { 60 | this.id = id; 61 | } 62 | 63 | public String getUserId() { 64 | return userId; 65 | } 66 | 67 | public void setUserId(String userId) { 68 | this.userId = userId; 69 | } 70 | 71 | public String getUserName() { 72 | return userName; 73 | } 74 | 75 | public void setUserName(String userName) { 76 | this.userName = userName; 77 | } 78 | 79 | public String getPassword() { 80 | return password; 81 | } 82 | 83 | public void setPassword(String password) { 84 | this.password = password; 85 | } 86 | 87 | public String getDealpassword() { 88 | return dealpassword; 89 | } 90 | 91 | public void setDealpassword(String dealpassword) { 92 | this.dealpassword = dealpassword; 93 | } 94 | 95 | public String getSex() { 96 | return sex; 97 | } 98 | 99 | public void setSex(String sex) { 100 | this.sex = sex; 101 | } 102 | 103 | public String getType() { 104 | return type; 105 | } 106 | 107 | public void setType(String type) { 108 | this.type = type; 109 | } 110 | 111 | public String getUserLevel() { 112 | return userLevel; 113 | } 114 | 115 | public void setUserLevel(String userLevel) { 116 | this.userLevel = userLevel; 117 | } 118 | 119 | public String getPhone() { 120 | return phone; 121 | } 122 | 123 | public void setPhone(String phone) { 124 | this.phone = phone; 125 | } 126 | 127 | public String getMobile() { 128 | return mobile; 129 | } 130 | 131 | public void setMobile(String mobile) { 132 | this.mobile = mobile; 133 | } 134 | 135 | public String getEmail() { 136 | return email; 137 | } 138 | 139 | public void setEmail(String email) { 140 | this.email = email; 141 | } 142 | 143 | public String getWeChat() { 144 | return weChat; 145 | } 146 | 147 | public void setWeChat(String weChat) { 148 | this.weChat = weChat; 149 | } 150 | 151 | public String getTelegram() { 152 | return telegram; 153 | } 154 | 155 | public void setTelegram(String telegram) { 156 | this.telegram = telegram; 157 | } 158 | 159 | public String getAddress() { 160 | return address; 161 | } 162 | 163 | public void setAddress(String address) { 164 | this.address = address; 165 | } 166 | 167 | public String getZipCode() { 168 | return zipCode; 169 | } 170 | 171 | public void setZipCode(String zipCode) { 172 | this.zipCode = zipCode; 173 | } 174 | 175 | public String getRoleId() { 176 | return roleId; 177 | } 178 | 179 | public void setRoleId(String roleId) { 180 | this.roleId = roleId; 181 | } 182 | 183 | public String getStatusFlag() { 184 | return statusFlag; 185 | } 186 | 187 | public void setStatusFlag(String statusFlag) { 188 | this.statusFlag = statusFlag; 189 | } 190 | 191 | public String getOtherInfo() { 192 | return otherInfo; 193 | } 194 | 195 | public void setOtherInfo(String otherInfo) { 196 | this.otherInfo = otherInfo; 197 | } 198 | 199 | public Date getCreateTime() { 200 | return createTime; 201 | } 202 | 203 | public void setCreateTime(Date createTime) { 204 | this.createTime = createTime; 205 | } 206 | 207 | public String getLangType() { 208 | return langType; 209 | } 210 | 211 | public void setLangType(String langType) { 212 | this.langType = langType; 213 | } 214 | 215 | public String getPermissionLang() { 216 | return permissionLang; 217 | } 218 | 219 | public void setPermissionLang(String permissionLang) { 220 | this.permissionLang = permissionLang; 221 | } 222 | } -------------------------------------------------------------------------------- /src/main/java/com/pkh/dao/prop/PikaDayBean.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.prop; 2 | 3 | import lombok.Data; 4 | import lombok.ToString; 5 | 6 | @Data 7 | @ToString 8 | public class PikaDayBean { 9 | 10 | private long startTime; 11 | 12 | private long endTime; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/enums/RoleEnum.java: -------------------------------------------------------------------------------- 1 | package com.pkh.enums; 2 | 3 | public enum RoleEnum { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/enums/SexEnum.java: -------------------------------------------------------------------------------- 1 | package com.pkh.enums; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | * 性别枚举 7 | */ 8 | public enum SexEnum { 9 | BOY(0, "男"), 10 | GIRL(1, "女"), 11 | OTHERS(2, "保密"); 12 | 13 | /** 14 | * 性别编码 15 | */ 16 | private Integer code; 17 | 18 | /** 19 | * 性别描述 20 | */ 21 | private String description; 22 | 23 | /** 24 | * 构造函数 25 | * 26 | * @param code 性别编码 27 | * @param description 性别描述 28 | */ 29 | SexEnum(Integer code, String description) { 30 | this.code = code; 31 | this.description = description; 32 | } 33 | 34 | /** 35 | * 根据编码获取性别枚举 36 | * 37 | * @param code 性别编码 38 | * @return 39 | */ 40 | public static SexEnum getByCode(Integer code) { 41 | for (SexEnum e : SexEnum.values()) { 42 | if (Objects.equals(code, e.getCode())) { 43 | return e; 44 | } 45 | } 46 | return null; 47 | } 48 | 49 | public Integer getCode() { 50 | return code; 51 | } 52 | 53 | public void setCode(Integer code) { 54 | this.code = code; 55 | } 56 | 57 | public String getDescription() { 58 | return description; 59 | } 60 | 61 | public void setDescription(String description) { 62 | this.description = description; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/filter/JWTFilter.java: -------------------------------------------------------------------------------- 1 | package com.pkh.filter; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.pkh.commons.jwt.JWTToken; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter; 7 | import org.springframework.util.StringUtils; 8 | 9 | import javax.servlet.ServletRequest; 10 | import javax.servlet.ServletResponse; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | import java.io.IOException; 14 | import java.util.HashMap; 15 | import java.util.Map; 16 | 17 | @Slf4j 18 | public class JWTFilter extends BasicHttpAuthenticationFilter { 19 | private static String LOGIN_SIGN = "X-Token"; 20 | 21 | @Override 22 | protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { 23 | String token = ((HttpServletRequest) request).getHeader(LOGIN_SIGN); 24 | if (!StringUtils.hasLength(token)) { 25 | try { 26 | setReturnInfo((HttpServletResponse) response, 401, "请求token为空"); 27 | } catch (IOException e) { 28 | log.info("isAccessAllowed 出错: {}", e.getMessage()); 29 | } 30 | return false; 31 | } 32 | return executeLogin(request, response); 33 | } 34 | 35 | @Override 36 | protected boolean executeLogin(ServletRequest request, ServletResponse response) { 37 | HttpServletRequest httpServletRequest = (HttpServletRequest) request; 38 | HttpServletResponse httpServletResponse = (HttpServletResponse) response; 39 | String token = httpServletRequest.getHeader(LOGIN_SIGN); 40 | 41 | JWTToken jwtToken = new JWTToken(token); 42 | // 提交给realm进行登录,如果错误他会抛出异常并被捕获 43 | try { 44 | this.getSubject(request, response).login(jwtToken); 45 | } catch (Exception e) { 46 | try { 47 | setReturnInfo(httpServletResponse,401,"登录认证出现异常"); 48 | } catch (IOException ex) { 49 | log.info(e.getMessage()); 50 | } 51 | return false; 52 | } 53 | return true; 54 | } 55 | 56 | @Override 57 | protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { 58 | return super.onAccessDenied(request, response); 59 | } 60 | 61 | private static void setReturnInfo(HttpServletResponse response, int status, String msg) throws IOException { 62 | response.setContentType("application/json;charset=utf-8"); 63 | Map result = new HashMap<>(); 64 | result.put("status", String.valueOf(status)); 65 | result.put("msg", msg); 66 | 67 | ObjectMapper mapper = new ObjectMapper(); 68 | String jsonRes = mapper.writeValueAsString(result); 69 | response.getWriter().write(jsonRes); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/filter/LogFilter.java: -------------------------------------------------------------------------------- 1 | package com.pkh.filter; 2 | 3 | import org.slf4j.MDC; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.core.Ordered; 6 | import org.springframework.web.filter.OncePerRequestFilter; 7 | 8 | import javax.servlet.FilterChain; 9 | import javax.servlet.ServletException; 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | import java.io.IOException; 13 | 14 | /** 15 | * OncePerRequestFilter是在一次外部请求中只过滤一次。 16 | * 对于服务器内部之间的forward等请求,不会再次执行过滤方法。 17 | */ 18 | @Configuration 19 | public class LogFilter extends OncePerRequestFilter implements Ordered { 20 | private final static String MDC_TRACE_ID = "traceId"; 21 | 22 | @Override 23 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { 24 | String traceIDStr = getMdcTraceId(); 25 | MDC.put(MDC_TRACE_ID, traceIDStr); 26 | filterChain.doFilter(request, response); 27 | MDC.clear(); 28 | } 29 | 30 | /** 31 | * 生产tranceId 32 | * 33 | * @return tranceID 34 | */ 35 | private String getMdcTraceId() { 36 | long currentTime = System.nanoTime(); 37 | return String.join("_", MDC_TRACE_ID, String.valueOf(currentTime)); 38 | } 39 | 40 | @Override 41 | public int getOrder() { 42 | return Ordered.HIGHEST_PRECEDENCE; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/handler/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.pkh.handler; 2 | 3 | import com.pkh.bean.response.PikaResponse; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.validation.FieldError; 7 | import org.springframework.web.bind.MethodArgumentNotValidException; 8 | import org.springframework.web.bind.annotation.ExceptionHandler; 9 | import org.springframework.web.bind.annotation.ResponseStatus; 10 | import org.springframework.web.bind.annotation.RestControllerAdvice; 11 | 12 | import javax.servlet.http.HttpServletRequest; 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | @RestControllerAdvice 17 | @Slf4j 18 | public class GlobalExceptionHandler { 19 | 20 | // 捕获空指针异常 21 | @ExceptionHandler(NullPointerException.class) 22 | @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 23 | public PikaResponse nullPointerExceptionRun(HttpServletRequest request, Throwable e) { 24 | String message = "发生了空指针异常!"; 25 | e.printStackTrace(); 26 | return new PikaResponse<>(getStatus(request).value()+"", message); 27 | } 28 | 29 | private HttpStatus getStatus(HttpServletRequest request) { 30 | Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); 31 | if (statusCode == null) { 32 | return HttpStatus.INTERNAL_SERVER_ERROR; 33 | } 34 | return HttpStatus.valueOf(statusCode); 35 | } 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | // 捕捉其他所有异常 47 | @ExceptionHandler(Exception.class) 48 | @ResponseStatus(HttpStatus.BAD_REQUEST) 49 | public PikaResponse globalException(HttpServletRequest request, Throwable ex) { 50 | ex.printStackTrace(); 51 | return new PikaResponse("'"+getStatus(request).value()+"'", ex.getMessage()); 52 | } 53 | 54 | // 参数校验异常 55 | @ResponseStatus(HttpStatus.BAD_REQUEST) 56 | @ExceptionHandler(MethodArgumentNotValidException.class) 57 | public PikaResponse handleValidationExceptions(MethodArgumentNotValidException ex) { 58 | Map errors = new HashMap<>(); 59 | String strErrors = ""; 60 | ex.getBindingResult().getAllErrors().forEach((error) -> { 61 | String fieldName = ((FieldError) error).getField(); 62 | String errorMessage = error.getDefaultMessage(); 63 | errors.put(fieldName, errorMessage); 64 | }); 65 | for (String error : errors.values()) { 66 | strErrors += error + ","; 67 | } 68 | 69 | return new PikaResponse("500", strErrors); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/interceptor/LogInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.pkh.interceptor; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.slf4j.MDC; 5 | import org.springframework.web.servlet.HandlerInterceptor; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | 11 | @Slf4j 12 | public class LogInterceptor implements HandlerInterceptor { 13 | 14 | private final static String MDC_TRACE_ID = "traceId"; 15 | 16 | @Override 17 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 18 | log.info("Interceptor PreHandle event"); 19 | String traceIDStr = getMdcTraceId(); 20 | MDC.put(MDC_TRACE_ID, traceIDStr); 21 | return true; 22 | } 23 | 24 | /** 25 | * 生产tranceId 26 | * 27 | * @return tranceID 28 | */ 29 | private String getMdcTraceId() { 30 | long currentTime = System.nanoTime(); 31 | return String.join("_", MDC_TRACE_ID, String.valueOf(currentTime)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/learn/pibatis/MapperImpl.java: -------------------------------------------------------------------------------- 1 | package com.pkh.learn.pibatis; 2 | 3 | import com.pkh.dao.po.User; 4 | 5 | import java.util.List; 6 | 7 | public class MapperImpl implements UserMapper { 8 | @Override 9 | public List getUser(String userId, String userName) { 10 | return null; 11 | } 12 | 13 | @Override 14 | public User getUserById(Long id) { 15 | return null; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/learn/pibatis/MapperProxyFactory.java: -------------------------------------------------------------------------------- 1 | package com.pkh.learn.pibatis; 2 | 3 | import java.lang.reflect.InvocationHandler; 4 | import java.lang.reflect.Method; 5 | import java.lang.reflect.Proxy; 6 | 7 | public class MapperProxyFactory { 8 | 9 | public static T getMapper(Class mapper) { 10 | Object mapperProxy = Proxy.newProxyInstance(MapperProxyFactory.class.getClassLoader(), new Class[]{mapper}, new InvocationHandler() { 11 | @Override 12 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 13 | return null; 14 | } 15 | }); 16 | return (T) mapperProxy; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/learn/pibatis/MyApplication.java: -------------------------------------------------------------------------------- 1 | package com.pkh.learn.pibatis; 2 | 3 | import com.pkh.dao.po.User; 4 | 5 | import java.util.List; 6 | 7 | public class MyApplication { 8 | public static void main(String[] args) { 9 | UserMapper userMapper = MapperProxyFactory.getMapper(UserMapper.class); 10 | List userList = userMapper.getUser("kangkang@pika.com", "kangkang"); 11 | 12 | UserMapper mapper = new MapperImpl(); 13 | List userList1 = mapper.getUser("kangkang@pika.com", "kangkang"); 14 | 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/learn/pibatis/Select.java: -------------------------------------------------------------------------------- 1 | package com.pkh.learn.pibatis; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target(ElementType.METHOD) 10 | public @interface Select { 11 | String value() default ""; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/learn/pibatis/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.pkh.learn.pibatis; 2 | 3 | import com.pkh.dao.po.User; 4 | 5 | import java.util.List; 6 | 7 | public interface UserMapper { 8 | 9 | @Select("select * from t_user where userId = #{userId} and userName = #{userName}") 10 | List getUser(String userId, String userName); 11 | 12 | User getUserById(Long id); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/learn/proxy/Coder.java: -------------------------------------------------------------------------------- 1 | package com.pkh.learn.proxy; 2 | 3 | public interface Coder { 4 | void coding(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/learn/proxy/Programmer.java: -------------------------------------------------------------------------------- 1 | package com.pkh.learn.proxy; 2 | 3 | import java.lang.reflect.InvocationHandler; 4 | import java.lang.reflect.Method; 5 | import java.lang.reflect.Proxy; 6 | 7 | public class Programmer implements Coder { 8 | @Override 9 | public void coding() { 10 | System.out.println("programmer is coding"); 11 | } 12 | 13 | public static void main(String[] args) { 14 | Programmer programmer = new Programmer(); 15 | Coder coderProxy = (Coder) Proxy.newProxyInstance(Programmer.class.getClassLoader(), new Class[]{Coder.class}, new InvocationHandler() { 16 | @Override 17 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 18 | System.out.println("方法:" + method.getName() + "()执行前"); 19 | Object invoke = method.invoke(programmer, args); 20 | System.out.println("方法:" + method.getName() + "()执行后"); 21 | return invoke; 22 | } 23 | }); 24 | coderProxy.coding(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/AdminService.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service; 2 | 3 | import com.pkh.bean.param.AdminListParam; 4 | import com.pkh.dao.po.admindb.AdminUser; 5 | 6 | import java.util.List; 7 | 8 | public interface AdminService { 9 | Integer countByParam(AdminListParam param); 10 | List getByParam(AdminListParam param); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/ArticleService.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service; 2 | 3 | public interface ArticleService { 4 | 5 | Long readArticle(String articleId); 6 | 7 | Long collectArticle(String articleId, String userId); 8 | 9 | Long cancelCollectArticle(String articleId, String userId); 10 | 11 | Long getArticleCollectCount(String articleId); 12 | 13 | Long likeArticle(String articleId, String userId); 14 | 15 | Long getArticleLikeCount(String articleId); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/CustomerService.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service; 2 | 3 | import com.pkh.bean.param.CustomerListParam; 4 | import com.pkh.dao.po.Customer; 5 | 6 | import java.util.List; 7 | 8 | public interface CustomerService { 9 | Integer countByParam(CustomerListParam param); 10 | List getByParam(CustomerListParam param); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/LoginService.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service; 2 | 3 | public interface LoginService { 4 | String login(String username, String password); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/RoleService.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service; 2 | 3 | import com.pkh.bean.param.RoleListParam; 4 | import com.pkh.dao.po.Role; 5 | 6 | import java.util.List; 7 | 8 | public interface RoleService { 9 | 10 | List getByParam(RoleListParam param); 11 | 12 | Integer countByParam(RoleListParam param); 13 | 14 | List getByCondition(RoleListParam param); 15 | 16 | Integer countByCondition(RoleListParam param); 17 | 18 | int add(Role role); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/StockService.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service; 2 | 3 | public interface StockService { 4 | Boolean deductStock(String productId, int count); 5 | 6 | Boolean deductStockWithRedisson(String productId, int count); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service; 2 | 3 | import com.pkh.bean.param.UserListParam; 4 | import com.pkh.dao.po.Rights; 5 | import com.pkh.dao.po.User; 6 | 7 | import java.util.List; 8 | 9 | public interface UserService { 10 | 11 | List getByParam(UserListParam param); 12 | 13 | Integer countByParam(UserListParam param); 14 | 15 | List getByCondition(UserListParam param); 16 | 17 | Integer countByCondition(UserListParam param); 18 | 19 | int add(User param); 20 | 21 | User getByUserId(String userId); 22 | 23 | List getRights(User user); 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/VipService.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service; 2 | 3 | import java.util.List; 4 | 5 | public interface VipService { 6 | 7 | List list(); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/impl/AdminServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service.impl; 2 | 3 | import com.pkh.bean.param.AdminListParam; 4 | import com.pkh.dao.mapper.AdminUserMapper; 5 | import com.pkh.dao.po.admindb.AdminUser; 6 | import com.pkh.service.AdminService; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.util.ObjectUtils; 9 | 10 | import javax.annotation.Resource; 11 | import java.util.HashMap; 12 | import java.util.List; 13 | import java.util.Map; 14 | 15 | @Service 16 | public class AdminServiceImpl implements AdminService { 17 | 18 | @Resource 19 | AdminUserMapper adminUserMapper; 20 | 21 | @Override 22 | public Integer countByParam(AdminListParam param) { 23 | Map map = new HashMap<>(); 24 | return adminUserMapper.countByCondition(map); 25 | } 26 | 27 | @Override 28 | public List getByParam(AdminListParam param) { 29 | int offset = 0; 30 | if (!ObjectUtils.isEmpty(param.getPageIndex()) && !ObjectUtils.isEmpty(param.getPageSize())) { 31 | offset = (param.getPageIndex() - 1) * param.getPageSize(); 32 | } 33 | Map map = new HashMap<>(); 34 | return adminUserMapper.selectByCondition(map, offset, param.getPageSize()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/impl/ArticleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service.impl; 2 | 3 | import com.pkh.service.ArticleService; 4 | import com.pkh.util.RedisUtil; 5 | import org.springframework.stereotype.Service; 6 | 7 | import javax.annotation.Resource; 8 | 9 | @Service 10 | public class ArticleServiceImpl implements ArticleService { 11 | 12 | @Resource 13 | RedisUtil redisUtil; 14 | 15 | @Override 16 | public Long readArticle(String articleId) { 17 | String key = this.generateArticleReadKey(articleId); 18 | return redisUtil.incur(key); 19 | } 20 | 21 | @Override 22 | public Long collectArticle(String articleId, String userId) { 23 | String key = this.generateArticleCollectKey(articleId); 24 | return redisUtil.addSet(key, userId); 25 | } 26 | 27 | @Override 28 | public Long cancelCollectArticle(String articleId, String userId) { 29 | String key = this.generateArticleCollectKey(articleId); 30 | return redisUtil.removeSet(key, userId); 31 | } 32 | 33 | @Override 34 | public Long likeArticle(String articleId, String userId) { 35 | String key = this.generateArticleLikeKey(articleId); 36 | redisUtil.publish("__bili_like__", userId + ": " + articleId); 37 | return redisUtil.addSet(key, userId); 38 | } 39 | 40 | @Override 41 | public Long getArticleLikeCount(String articleId) { 42 | String key = this.generateArticleLikeKey(articleId); 43 | return redisUtil.countSet(key); 44 | } 45 | 46 | @Override 47 | public Long getArticleCollectCount(String articleId) { 48 | String key = this.generateArticleCollectKey(articleId); 49 | return redisUtil.countSet(key); 50 | } 51 | 52 | /** 53 | * 文章阅读量计数,生成对应Redis的Key 54 | * 55 | * @param articleId 文章Id 56 | * @return 57 | */ 58 | private String generateArticleReadKey(String articleId) { 59 | return "article:read:count:" + articleId; 60 | } 61 | 62 | /** 63 | * 文章收藏记录,生成对应Redis的Key 64 | * @param articleId 文章Id 65 | * @return 66 | */ 67 | private String generateArticleCollectKey(String articleId) { 68 | return "article:collect:user:count:" + articleId; 69 | } 70 | 71 | /** 72 | * 文章点赞记录,生成对应Redis的Key 73 | * @param articleId 74 | * @return 75 | */ 76 | private String generateArticleLikeKey(String articleId) { 77 | return "article:like:user:count:" + articleId; 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/impl/LoginServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service.impl; 2 | 3 | import com.pkh.service.LoginService; 4 | import com.pkh.util.JWTUtil; 5 | import org.springframework.stereotype.Service; 6 | 7 | @Service 8 | public class LoginServiceImpl implements LoginService { 9 | @Override 10 | public String login(String username, String password) { 11 | String token = JWTUtil.sign(username, password); 12 | return token; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/impl/RoleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service.impl; 2 | 3 | import com.pkh.bean.param.RoleListParam; 4 | import com.pkh.dao.mapper.RoleMapper; 5 | import com.pkh.dao.po.Role; 6 | import com.pkh.service.RoleService; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.util.ObjectUtils; 9 | 10 | import javax.annotation.Resource; 11 | import java.util.HashMap; 12 | import java.util.List; 13 | import java.util.Map; 14 | 15 | @Service 16 | public class RoleServiceImpl implements RoleService { 17 | 18 | @Resource 19 | RoleMapper roleMapper; 20 | 21 | @Override 22 | public List getByParam(RoleListParam param) { 23 | Integer offset = 0; 24 | if (!ObjectUtils.isEmpty(param.getPageIndex()) && !ObjectUtils.isEmpty(param.getPageSize())) { 25 | offset = (param.getPageIndex() - 1) * param.getPageSize(); 26 | } 27 | param.setOffset(offset); 28 | return roleMapper.selectByParam(param); 29 | } 30 | 31 | @Override 32 | public Integer countByParam(RoleListParam param) { 33 | return roleMapper.countByParam(param); 34 | } 35 | 36 | @Override 37 | public List getByCondition(RoleListParam param) { 38 | Map map = new HashMap<>(); 39 | map.put("role_no", param.getRoleNo()); 40 | map.put("name", param.getName()); 41 | map.put("status", param.getStatus()); 42 | map.put("type", param.getType()); 43 | return roleMapper.selectByCondition(map); 44 | } 45 | 46 | @Override 47 | public Integer countByCondition(RoleListParam param) { 48 | Map map = new HashMap<>(); 49 | map.put("role_no", param.getRoleNo()); 50 | map.put("name", param.getName()); 51 | map.put("status", param.getStatus()); 52 | map.put("type", param.getType()); 53 | return roleMapper.countByCondition(map); 54 | } 55 | 56 | @Override 57 | public int add(Role role) { 58 | return roleMapper.insertSelective(role); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/impl/StockServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service.impl; 2 | 3 | import com.pkh.service.StockService; 4 | import com.pkh.util.RedisUtil; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.redisson.api.RLock; 7 | import org.redisson.api.RedissonClient; 8 | import org.springframework.data.redis.core.RedisTemplate; 9 | import org.springframework.stereotype.Service; 10 | 11 | import javax.annotation.Resource; 12 | import java.util.UUID; 13 | 14 | @Service 15 | @Slf4j 16 | public class StockServiceImpl implements StockService { 17 | 18 | @Resource 19 | RedisUtil redisUtil; 20 | 21 | @Resource 22 | RedissonClient redissonClient; 23 | 24 | private static final String LOCK_KEY = "stock_lock"; 25 | 26 | @Override 27 | public Boolean deductStock(String productId, int count) { 28 | String lockKey = "stock_lock:" + productId; 29 | String requestId = UUID.randomUUID().toString(); 30 | try { 31 | // 尝试上锁(分布式锁) 32 | boolean isLockAcquired = redisUtil.tryGetDistributedLock(lockKey, requestId, RedisUtil.EXPIRE_TIME); 33 | if (!isLockAcquired) { 34 | // 上锁失败,可以选择重试或者直接返回失败 35 | throw new RuntimeException("Failed to acquire distributed lock for product: " + productId); 36 | } 37 | 38 | // 上锁成功,执行扣减库存操作 39 | log.info("执行扣减库存逻辑"); 40 | 41 | } finally { 42 | // 释放分布式锁 43 | redisUtil.releaseDistributedLock(lockKey, requestId); 44 | } 45 | return true; 46 | } 47 | 48 | @Override 49 | public Boolean deductStockWithRedisson(String productId, int count) { 50 | RLock lock = redissonClient.getLock(LOCK_KEY + productId); 51 | try { 52 | // 尝试上锁(分布式锁) 53 | lock.lock(); 54 | // 上锁成功,执行扣减库存操作 55 | log.info("执行扣减库存逻辑"); 56 | return true; 57 | } finally { 58 | // 释放分布式锁 59 | lock.unlock(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service.impl; 2 | 3 | import com.pkh.bean.param.UserListParam; 4 | import com.pkh.bean.vo.UserVo; 5 | import com.pkh.dao.mapper.UserMapper; 6 | import com.pkh.dao.po.Rights; 7 | import com.pkh.dao.po.User; 8 | import com.pkh.enums.SexEnum; 9 | import com.pkh.service.UserService; 10 | import javafx.beans.binding.ObjectBinding; 11 | import lombok.extern.slf4j.Slf4j; 12 | import org.springframework.beans.BeanUtils; 13 | import org.springframework.stereotype.Service; 14 | import org.springframework.util.CollectionUtils; 15 | import org.springframework.util.ObjectUtils; 16 | 17 | import javax.annotation.Resource; 18 | import java.util.*; 19 | 20 | @Service 21 | @Slf4j 22 | public class UserServiceImpl implements UserService { 23 | 24 | @Resource 25 | UserMapper userMapper; 26 | 27 | @Override 28 | public List getByParam(UserListParam param) { 29 | int offset = 0; 30 | if (!ObjectUtils.isEmpty(param.getPageIndex()) && !ObjectUtils.isEmpty(param.getPageSize())) { 31 | offset = (param.getPageIndex() - 1) * param.getPageSize(); 32 | } 33 | param.setOffset(offset); 34 | List users = userMapper.selectByParam(param); 35 | // users处理逻辑 kangkang@pika.com 36 | users.stream().filter(Objects::nonNull).filter(item -> !ObjectUtils.isEmpty(item.getUserId())).forEach(item -> { 37 | String userId = item.getUserId(); 38 | int index = userId.indexOf('@'); 39 | item.setUserName(userId.substring(0,index)); 40 | }); 41 | return users; 42 | } 43 | 44 | @Override 45 | public Integer countByParam(UserListParam param) { 46 | return userMapper.countByParam(param); 47 | } 48 | 49 | @Override 50 | public List getByCondition(UserListParam param) { 51 | int offset = 0; 52 | if (!ObjectUtils.isEmpty(param.getPageIndex()) && !ObjectUtils.isEmpty(param.getPageSize())) { 53 | offset = (param.getPageIndex() - 1) * param.getPageSize(); 54 | } 55 | Map map = new HashMap<>(); 56 | map.put("user_id", param.getUserId()); 57 | map.put("sex", param.getSex()); 58 | return userMapper.selectByCondition(map, offset, param.getPageSize()); 59 | } 60 | 61 | @Override 62 | public Integer countByCondition(UserListParam param) { 63 | Map map = new HashMap<>(); 64 | map.put("user_id", param.getUserId()); 65 | map.put("sex", param.getSex()); 66 | return userMapper.countByCondition(map); 67 | } 68 | 69 | @Override 70 | public int add(User param) { 71 | return userMapper.insertSelective(param); 72 | } 73 | 74 | @Override 75 | public User getByUserId(String userId) { 76 | // Map map = new HashMap<>(); 77 | // map.put("user_id", userId); 78 | // List userList = userMapper.selectByCondition(map, null, null); 79 | // if (!CollectionUtils.isEmpty(userList)) { 80 | // return userList.get(0); 81 | // } 82 | // return null; 83 | 84 | return new User("pika@163.com"); 85 | } 86 | 87 | @Override 88 | public List getRights(User user) { 89 | List rightsList; 90 | int sex = Integer.parseInt(user.getSex()); 91 | if (SexEnum.BOY.getCode() == sex) { 92 | rightsList = getBoyRights(); 93 | } else if (SexEnum.GIRL.getCode() == sex) { 94 | rightsList = getGirlRights(); 95 | } else { 96 | rightsList = getOtherRights(); 97 | } 98 | return rightsList; 99 | } 100 | 101 | 102 | 103 | private List getBoyRights() { 104 | List rightsList = new ArrayList<>(); 105 | return rightsList; 106 | } 107 | 108 | private List getGirlRights() { 109 | List rightsList = new ArrayList<>(); 110 | return rightsList; 111 | } 112 | 113 | private List getOtherRights() { 114 | List rightsList = new ArrayList<>(); 115 | return rightsList; 116 | } 117 | 118 | 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/service/impl/VipServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service.impl; 2 | 3 | import com.pkh.dao.po.Vip; 4 | import com.pkh.service.VipService; 5 | import org.springframework.stereotype.Service; 6 | 7 | import java.util.Arrays; 8 | import java.util.List; 9 | 10 | @Service 11 | public class VipServiceImpl implements VipService { 12 | 13 | public List list() { 14 | Vip bob = new Vip(1,"bob","microsoft", "US"); 15 | Vip kangkang = new Vip(5,"kangkang","ali", "CN"); 16 | Vip alice = new Vip(4,"alice","apple", "US"); 17 | Vip jane = new Vip(3,"jane","intel", "US-10-04"); 18 | Vip jack = new Vip(2,"jack","ibm", "2004-US-03"); 19 | return Arrays.asList(bob, kangkang, alice, jane, jack); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/util/HttpUtil.java: -------------------------------------------------------------------------------- 1 | package com.pkh.util; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import org.apache.hc.client5.http.config.RequestConfig; 5 | import org.apache.hc.client5.http.impl.DefaultHttpRequestRetryStrategy; 6 | import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; 7 | import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; 8 | import org.apache.hc.client5.http.impl.classic.HttpClients; 9 | import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; 10 | import org.apache.hc.client5.http.socket.ConnectionSocketFactory; 11 | import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory; 12 | import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; 13 | import org.apache.hc.core5.http.ClassicHttpRequest; 14 | import org.apache.hc.core5.http.ContentType; 15 | import org.apache.hc.core5.http.HttpEntity; 16 | import org.apache.hc.core5.http.HttpStatus; 17 | import org.apache.hc.core5.http.config.Registry; 18 | import org.apache.hc.core5.http.config.RegistryBuilder; 19 | import org.apache.hc.core5.http.io.entity.EntityUtils; 20 | import org.apache.hc.core5.http.io.entity.StringEntity; 21 | import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; 22 | import org.apache.hc.core5.util.Timeout; 23 | import org.slf4j.Logger; 24 | import org.slf4j.LoggerFactory; 25 | 26 | import javax.net.ssl.SSLContext; 27 | import javax.net.ssl.TrustManager; 28 | import javax.net.ssl.X509TrustManager; 29 | import java.io.IOException; 30 | import java.io.UnsupportedEncodingException; 31 | import java.net.URLEncoder; 32 | import java.security.KeyManagementException; 33 | import java.security.NoSuchAlgorithmException; 34 | import java.security.cert.CertificateException; 35 | import java.util.ArrayList; 36 | import java.util.Iterator; 37 | import java.util.List; 38 | import java.util.Map; 39 | 40 | public class HttpUtil { 41 | 42 | private static Logger logger = LoggerFactory.getLogger(HttpUtil.class); 43 | // utf-8字符编码 44 | private static final String CHARSET_UTF_8 = "utf-8"; 45 | 46 | // 连接管理器 47 | private static PoolingHttpClientConnectionManager pool; 48 | 49 | // 请求配置 50 | private static RequestConfig requestConfig; 51 | 52 | static { 53 | try { 54 | SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(createIgnoreVerifySSL()); 55 | // 配置同时支持 HTTP 和 HTPPS 56 | Registry socketFactoryRegistry = RegistryBuilder.create() 57 | .register("http", PlainConnectionSocketFactory.getSocketFactory()) 58 | .register("https", sslsf).build(); 59 | // 初始化连接管理器 60 | pool = new PoolingHttpClientConnectionManager(socketFactoryRegistry); 61 | // 将最大连接数增加到200,实际项目最好从配置文件中读取这个值 62 | pool.setMaxTotal(20); 63 | // 设置最大路由 64 | pool.setDefaultMaxPerRoute(20); 65 | // 根据默认超时限制初始化requestConfig 66 | requestConfig = RequestConfig.custom() 67 | .setConnectionRequestTimeout(Timeout.ofMilliseconds(5000)) 68 | .setConnectTimeout(Timeout.ofMilliseconds(5000)).build(); 69 | } catch (NoSuchAlgorithmException | KeyManagementException e) { 70 | logger.error("HttpClientUtil.static error: {}", e.getMessage()); 71 | } 72 | } 73 | private static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException { 74 | SSLContext sc = SSLContext.getInstance("TLSv1.2"); 75 | 76 | // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法 77 | X509TrustManager trustManager = new X509TrustManager() { 78 | @Override 79 | public void checkClientTrusted( 80 | java.security.cert.X509Certificate[] paramArrayOfX509Certificate, 81 | String paramString) throws CertificateException { 82 | } 83 | 84 | @Override 85 | public void checkServerTrusted( 86 | java.security.cert.X509Certificate[] paramArrayOfX509Certificate, 87 | String paramString) throws CertificateException { 88 | } 89 | 90 | @Override 91 | public java.security.cert.X509Certificate[] getAcceptedIssuers() { 92 | return null; 93 | } 94 | }; 95 | 96 | sc.init(null, new TrustManager[]{trustManager}, null); 97 | return sc; 98 | } 99 | 100 | /** 101 | * 发送post请求 102 | * 103 | * @param url 请求地址 104 | * @param param 请求参数 105 | * @param charset 参数字符集 106 | * @return 107 | */ 108 | public static String doPost(String url, JSONObject param, String charset) { 109 | String result = null; 110 | try { 111 | ClassicHttpRequest httpPost = ClassicRequestBuilder.post(url).build(); 112 | httpPost.setEntity(new StringEntity(param.toJSONString(), ContentType.APPLICATION_JSON)); 113 | result = sendHttp(httpPost); 114 | } catch (Exception ex) { 115 | ex.printStackTrace(); 116 | } 117 | return result; 118 | } 119 | 120 | /** 121 | * 发送get请求 122 | * 123 | * @param httpUrl 请求地址 124 | */ 125 | public static String doGet(String httpUrl, Map paramMap, Map headMap) throws UnsupportedEncodingException { 126 | String param = convert2String(paramMap); 127 | ClassicHttpRequest httpGet = ClassicRequestBuilder.get(httpUrl + (param.length() == 0 ? "" : "?" + param)) 128 | .build(); 129 | for (Iterator it = headMap.keySet().iterator(); it.hasNext(); ) { 130 | String key = it.next(); 131 | String value = headMap.get(key); 132 | httpGet.setHeader(key, value); 133 | } 134 | return sendHttp(httpGet); 135 | } 136 | 137 | private static String sendHttp(ClassicHttpRequest httpRequest) { 138 | CloseableHttpResponse response = null; 139 | // 响应内容 140 | String responseContent = null; 141 | try { 142 | CloseableHttpClient httpClient = getHttpClient(); 143 | response = httpClient.execute(httpRequest); 144 | HttpEntity entity = response.getEntity(); 145 | if (response.getCode() != HttpStatus.SC_OK) { 146 | throw new Exception("HTTP Request is not success, Response code is " + response.getCode() + "Reason phrase is" + response.getReasonPhrase()); 147 | } 148 | responseContent = EntityUtils.toString(entity, CHARSET_UTF_8); 149 | EntityUtils.consume(entity); 150 | 151 | } catch (Exception e) { 152 | logger.error("HttpClientUtil sendHttpPost error ", e); 153 | } finally { 154 | try { 155 | // 释放资源 156 | if (response != null) { 157 | response.close(); 158 | } 159 | } catch (IOException e) { 160 | logger.error("HttpClientUtil sendHttpPost close error ", e); 161 | } 162 | } 163 | return responseContent; 164 | } 165 | 166 | /** 167 | * 把Map转换为字符串类型 168 | * 169 | * @param parameterMap 字符串Map 170 | * @return 171 | * @throws UnsupportedEncodingException 172 | */ 173 | public static String convert2String(Map parameterMap) throws UnsupportedEncodingException { 174 | List paramList = new ArrayList<>(); 175 | if (parameterMap != null) { 176 | Iterator iterator = parameterMap.keySet().iterator(); 177 | for (;iterator.hasNext();) { 178 | String key = iterator.next(); 179 | String value; 180 | if (parameterMap.get(key) != null) { 181 | value = parameterMap.get(key); 182 | } else { 183 | value = ""; 184 | } 185 | paramList.add(URLEncoder.encode(key, CHARSET_UTF_8) + "=" + URLEncoder.encode(value, CHARSET_UTF_8)); 186 | } 187 | } 188 | return String.join("&", paramList); 189 | } 190 | 191 | /** 192 | * 获取一个客户端对象 193 | * 194 | * @return 195 | */ 196 | public static CloseableHttpClient getHttpClient() { 197 | CloseableHttpClient httpClient = HttpClients.custom() 198 | // 设置连接池管理 199 | .setConnectionManager(pool) 200 | // 设置请求配置 201 | .setDefaultRequestConfig(requestConfig) 202 | // 设置重试次数 203 | .setRetryStrategy(new DefaultHttpRequestRetryStrategy()) 204 | .build(); 205 | 206 | return httpClient; 207 | } 208 | 209 | } 210 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/util/JWTUtil.java: -------------------------------------------------------------------------------- 1 | package com.pkh.util; 2 | 3 | import com.auth0.jwt.JWT; 4 | import com.auth0.jwt.JWTVerifier; 5 | import com.auth0.jwt.algorithms.Algorithm; 6 | import com.auth0.jwt.exceptions.JWTDecodeException; 7 | import com.auth0.jwt.interfaces.DecodedJWT; 8 | import com.pkh.dao.po.User; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.apache.shiro.SecurityUtils; 11 | import org.springframework.util.ObjectUtils; 12 | 13 | import java.util.Date; 14 | 15 | @Slf4j 16 | public class JWTUtil { 17 | // 过期时间(分钟) 18 | private static final long EXPIRE_TIME = 6*60 * 60 * 1000; 19 | 20 | public static final long REDIS_TIME = 6*3600L; 21 | 22 | /** 23 | * 校验token是否正确 24 | * 25 | * @param token 密钥 26 | * @param username 登录名 27 | * @param password 密码 28 | * @return 29 | */ 30 | public static boolean verify(String token, String username, String password) { 31 | try { 32 | Algorithm algorithm = Algorithm.HMAC256(password); 33 | 34 | JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build(); 35 | 36 | DecodedJWT jwt = verifier.verify(token); 37 | 38 | return true; 39 | } catch (Exception e) { 40 | return false; 41 | } 42 | } 43 | 44 | /** 45 | * 获取登录名 46 | * 47 | * @param token 48 | * @return 49 | */ 50 | public static String getUsername(String token) { 51 | try { 52 | DecodedJWT jwt = JWT.decode(token); 53 | 54 | return jwt.getClaim("username").asString(); 55 | } catch (JWTDecodeException e) { 56 | return null; 57 | } 58 | } 59 | 60 | /** 61 | * 生成签名 62 | * 63 | * @param username 64 | * @param password 65 | * @return 66 | */ 67 | public static String sign(String username, String password) { 68 | // 指定过期时间 69 | Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); 70 | 71 | Algorithm algorithm = Algorithm.HMAC256(password); 72 | 73 | String token = JWT.create() 74 | .withClaim("username", username) 75 | .withExpiresAt(date) 76 | .sign(algorithm); 77 | log.info("login-data:{}token:{}",date,token); 78 | 79 | return token; 80 | } 81 | 82 | /** 83 | * 获取当前登录名 84 | * 85 | * @return 86 | */ 87 | public static String getLoginUserName() { 88 | try { 89 | User user = (User) SecurityUtils.getSubject().getPrincipal(); 90 | if(ObjectUtils.isEmpty(user)){ 91 | return null; 92 | } 93 | return user.getUserName(); 94 | } catch (JWTDecodeException e) { 95 | return null; 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/util/RSAUtil.java: -------------------------------------------------------------------------------- 1 | package com.pkh.util; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import org.apache.tomcat.util.codec.binary.Base64; 5 | 6 | import javax.crypto.Cipher; 7 | import java.security.KeyFactory; 8 | import java.security.interfaces.RSAPrivateKey; 9 | import java.security.interfaces.RSAPublicKey; 10 | import java.security.spec.PKCS8EncodedKeySpec; 11 | import java.security.spec.X509EncodedKeySpec; 12 | 13 | public class RSAUtil { 14 | private static JSONObject keyMap=new JSONObject(); 15 | 16 | static { 17 | keyMap.put("ANTPOOL_PUBLIC_KEY","MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk+89V7vpOj1rG6bTAKYM56qmFLwNCBVDJ3MltVVtxVUUByqc5b6u909MmmrLBqS//PWC6zc3wZzU1+ayh8xbUAEZuA3EjlPHIaFIVIz04RaW10+1xnby/RQE23tDqsv9a2jv/axjE/27b62nzvCWeItu1kNQ3MGdcuqKjke+LKhQ7nWPRCOd/ffVqSuRvG0YfUEkOz/6UpsPr6vrI331hWRB4DlYy8qFUmDsyvvExe4NjZWblXCqkEXRRAhi2SQRCl3teGuIHtDUxCskRIDiaMD+Qt2Yp+Vvbz6hUiqIWSIH1BoHJer/JOq2/O6X3cmuppU4AdVNgy8Bq236iXvrMQIDAQAB"); 18 | } 19 | 20 | private static String getPublicKey(String keyName) { 21 | return keyMap.getString(keyName); 22 | } 23 | 24 | /** 25 | * RSA公钥加密 26 | * 27 | * @param str 加密字符串 28 | * @param publicKeyName 公钥名称 29 | * @return 密文 30 | * @throws Exception 加密过程中的异常信息 31 | */ 32 | public static String encrypt(String str, String publicKeyName) throws Exception { 33 | String publicKey= getPublicKey(publicKeyName); 34 | //base64编码的公钥 35 | byte[] decoded = Base64.decodeBase64(publicKey); 36 | RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded)); 37 | 38 | //RSA加密 39 | Cipher cipher = Cipher.getInstance("RSA"); 40 | cipher.init(Cipher.ENCRYPT_MODE, pubKey); 41 | byte[] codeByte=cipher.doFinal(str.getBytes("UTF-8")); 42 | String outStr = Base64.encodeBase64String(codeByte); 43 | return outStr; 44 | } 45 | 46 | /** 47 | * RSA私钥解密 48 | * 49 | * @param str 加密字符串 50 | * @param privateKeyName 私钥名称 51 | * @return 铭文 52 | * @throws Exception 解密过程中的异常信息 53 | */ 54 | public static String decrypt(String str, String privateKeyName) throws Exception { 55 | //64位解码加密后的字符串 56 | byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8")); 57 | //base64编码的私钥 58 | byte[] decoded = Base64.decodeBase64(privateKeyName); 59 | RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); 60 | //RSA解密 61 | Cipher cipher = Cipher.getInstance("RSA"); 62 | cipher.init(Cipher.DECRYPT_MODE, priKey); 63 | String outStr = new String(cipher.doFinal(inputByte)); 64 | return outStr; 65 | } 66 | } 67 | 68 | -------------------------------------------------------------------------------- /src/main/java/com/pkh/util/RedisUtil.java: -------------------------------------------------------------------------------- 1 | package com.pkh.util; 2 | 3 | import org.springframework.data.redis.core.RedisTemplate; 4 | import org.springframework.data.redis.core.SetOperations; 5 | import org.springframework.data.redis.core.ValueOperations; 6 | import org.springframework.data.redis.core.script.DefaultRedisScript; 7 | import org.springframework.stereotype.Component; 8 | 9 | import javax.annotation.Resource; 10 | import java.util.Collections; 11 | import java.util.concurrent.TimeUnit; 12 | 13 | @Component 14 | public class RedisUtil { 15 | 16 | public static final String LOCK_SUCCESS = "OK"; 17 | public static final String SET_IF_NOT_EXIST = "NX"; 18 | public static final String SET_WITH_EXPIRE_TIME = "PX"; 19 | // 锁的默认过期时间,防止死锁 20 | public static final long EXPIRE_TIME = 100 * 1000; 21 | 22 | @Resource 23 | RedisTemplate redisTemplate; 24 | 25 | /** 26 | * 设置Redis键值对 27 | * set key 28 | * 29 | * @param key Redis键 30 | * @param value Redis值 31 | * 32 | */ 33 | public boolean set(final String key, final Object value) { 34 | try { 35 | ValueOperations operations = redisTemplate.opsForValue(); 36 | operations.set(key, value); 37 | return true; 38 | } catch (Exception e) { 39 | throw e; 40 | } 41 | } 42 | 43 | /** 44 | * 设置Redis键值对,包含Redis的过期时间 45 | * 46 | * @param key Redis键 47 | * @param value Redis值 48 | * @param expireTime 过期时间 49 | * @return 50 | */ 51 | public boolean set(final String key, Object value, Long expireTime) { 52 | try { 53 | ValueOperations operations = redisTemplate.opsForValue(); 54 | operations.set(key, value); 55 | redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); 56 | return true; 57 | } catch (Exception e) { 58 | throw e; 59 | } 60 | } 61 | 62 | /** 63 | * 根据Redis键,获取Redis值 64 | * get key 65 | * 66 | * @param key Redis键 67 | * @return 68 | */ 69 | public Object get(final String key) 70 | { 71 | ValueOperations operation = redisTemplate.opsForValue(); 72 | return operation.get(key); 73 | } 74 | 75 | /** 76 | * 根据Redis键,判断是否存在 77 | * 78 | * @param key Redis键值 79 | * @return 80 | */ 81 | public boolean exist(final String key) { 82 | Boolean isExist = redisTemplate.hasKey(key); 83 | if (null == isExist) { 84 | isExist = false; 85 | } 86 | return isExist; 87 | } 88 | 89 | /** 90 | * 根据Redis键,删除缓存 91 | * 92 | * @param key Redis键值 93 | * @return 94 | */ 95 | public boolean remove(final String key) { 96 | Boolean isDeleted = null; 97 | if (this.exist(key)) { 98 | isDeleted = redisTemplate.delete(key); 99 | } 100 | if (null == isDeleted) { 101 | isDeleted = false; 102 | } 103 | return isDeleted; 104 | } 105 | 106 | /** 107 | * 根据Redis键,设置有效期 108 | * 109 | * @param key Redis键值 110 | * @param seconds 有效期 111 | * @return 112 | */ 113 | public boolean expire(final String key, long seconds) { 114 | Boolean isExpired = redisTemplate.expire(key, seconds, TimeUnit.SECONDS); 115 | if (null == isExpired) { 116 | isExpired = false; 117 | } 118 | return isExpired; 119 | } 120 | 121 | /** 122 | * 根据Redis键,自增1 123 | * incur key 124 | * 125 | * @param key Redis键 126 | * @return 127 | */ 128 | public Long incur(final String key) { 129 | ValueOperations operations = redisTemplate.opsForValue(); 130 | return operations.increment(key); 131 | } 132 | 133 | /** 134 | * 根据Redis键,添加集合 135 | * sadd key value1, value2 136 | * 137 | * @param key Redis键 138 | * @param userId 集合中的元素(用户Id) 139 | * @return 成功添加到 Redis 集合中的元素数量 140 | */ 141 | public Long addSet(final String key, final String userId) { 142 | SetOperations operations = redisTemplate.opsForSet(); 143 | return operations.add(key, userId); 144 | } 145 | 146 | /** 147 | * 根据Redis键,移除集合中元素 148 | * srem key value 149 | * 150 | * @param key Redis键 151 | * @param userId 移除的元素(用户Id) 152 | * @return 被成功移除的元素的数量 153 | */ 154 | public Long removeSet(final String key, final String userId) { 155 | SetOperations operations = redisTemplate.opsForSet(); 156 | return operations.remove(key, userId); 157 | } 158 | 159 | /** 160 | * 根据Redis键,统计集合数量 161 | * scard key 162 | * 163 | * @param key Redis键 164 | * @return 165 | */ 166 | public Long countSet(final String key) { 167 | SetOperations operations = redisTemplate.opsForSet(); 168 | return operations.size(key); 169 | } 170 | 171 | /** 172 | * 尝试获取分布式锁 173 | * 174 | * @param lockKey 锁 175 | * @param requestId 请求标识 176 | * @param expireTime 超期时间 177 | * @return 是否获取成功 178 | */ 179 | public boolean tryGetDistributedLock(String lockKey, String requestId, long expireTime) { 180 | ValueOperations operations = redisTemplate.opsForValue(); 181 | Boolean result = operations.setIfAbsent(lockKey, requestId, expireTime, TimeUnit.MILLISECONDS); 182 | return Boolean.TRUE.equals(result); 183 | } 184 | 185 | /** 186 | * 释放分布式锁 187 | * 只有持有特定 requestId 的请求才能释放锁,防止其他请求错误地释放锁。 188 | * 189 | * @param lockKey 锁 190 | * @param requestId 请求标识 191 | * @return 是否释放成功 192 | */ 193 | public boolean releaseDistributedLock(String lockKey, String requestId) { 194 | String script = "if redis.call('get', KEYS[1]) == ARGV[1] then " + 195 | "return redis.call('del', KEYS[1]) " + 196 | "else " + 197 | "return 0 " + 198 | "end"; 199 | Long result = redisTemplate.execute( 200 | new DefaultRedisScript<>(script, Long.class), 201 | Collections.singletonList(lockKey), 202 | requestId); 203 | return result != null && result > 0; 204 | } 205 | 206 | /** 207 | * 发布消息 208 | * 209 | * @param channel 频道 210 | * @param msg 消息 211 | */ 212 | public void publish(final String channel, final String msg) { 213 | redisTemplate.convertAndSend(channel, msg); 214 | } 215 | 216 | } 217 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8082 2 | 3 | pkhdb.datasource.username=root 4 | pkhdb.datasource.password=123456 5 | pkhdb.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 6 | pkhdb.datasource.jdbc-url=jdbc:mysql://localhost:3306/pkhdb?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false&allowPublicKeyRetrieval=true 7 | 8 | admin.datasource.username=root 9 | admin.datasource.password=123456 10 | admin.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 11 | admin.datasource.jdbc-url=jdbc:mysql://localhost:3306/pkh_admindb?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false&allowPublicKeyRetrieval=true 12 | 13 | #mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl 14 | mybatis.mapper-locations=classpath:mapper/*.xml,classpath:mapper/admindb/*.xml 15 | 16 | # Redis 17 | spring.redis.host=127.0.0.1 18 | spring.redis.port=6379 19 | spring.redis.timeout=10s 20 | spring.redis.database=0 21 | spring.cache.redis.cache-null-values=true 22 | spring.redis.lettuce.pool.min-idle=0 23 | spring.redis.lettuce.pool.max-idle=8 24 | 25 | pikaday.startTime=1680796800000 26 | pikaday.endTime=1680883200000 27 | 28 | oa.baseUrl=http://localhost:8083/open-api 29 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | ${LOG_PATTERN} 13 | ${LOG_CHARSET} 14 | 15 | 16 | 17 | 18 | 19 | ${LOG_PATH}/java-week.log 20 | true 21 | 22 | ${LOG_PATH}/java-week.log.%d{yyyy-MM-dd} 23 | 30 24 | 25 | 26 | ${LOG_PATTERN} 27 | ${LOG_CHARSET} 28 | 29 | 30 | 31 | 32 | 33 | 1024 34 | true 35 | true 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/main/resources/mapper/RoleMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | id, role_no, `name`, `status`, `type`, create_time, update_time 15 | 16 | 17 | 18 | AND role_no = #{roleNo} 19 | 20 | 21 | AND `name` = #{name} 22 | 23 | 24 | AND `status` = #{status} 25 | 26 | 27 | AND `type` = #{type} 28 | 29 | 30 | AND create_time =]]]> #{createTime[0]} AND create_time #{createTime[1]} 31 | 32 | 33 | 34 | 40 | 41 | delete from t_role 42 | where id = #{id,jdbcType=BIGINT} 43 | 44 | 45 | insert into t_role (role_no, `name`, `status`, 46 | `type`, create_time, update_time 47 | ) 48 | values (#{roleNo,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{status,jdbcType=CHAR}, 49 | #{type,jdbcType=CHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP} 50 | ) 51 | 52 | 53 | insert into t_role 54 | 55 | 56 | role_no, 57 | 58 | 59 | `name`, 60 | 61 | 62 | `status`, 63 | 64 | 65 | `type`, 66 | 67 | 68 | create_time, 69 | 70 | 71 | update_time, 72 | 73 | 74 | 75 | 76 | #{roleNo,jdbcType=VARCHAR}, 77 | 78 | 79 | #{name,jdbcType=VARCHAR}, 80 | 81 | 82 | #{status,jdbcType=CHAR}, 83 | 84 | 85 | #{type,jdbcType=CHAR}, 86 | 87 | 88 | #{createTime,jdbcType=TIMESTAMP}, 89 | 90 | 91 | #{updateTime,jdbcType=TIMESTAMP}, 92 | 93 | 94 | 95 | 96 | update t_role 97 | 98 | 99 | role_no = #{roleNo,jdbcType=VARCHAR}, 100 | 101 | 102 | `name` = #{name,jdbcType=VARCHAR}, 103 | 104 | 105 | `status` = #{status,jdbcType=CHAR}, 106 | 107 | 108 | `type` = #{type,jdbcType=CHAR}, 109 | 110 | 111 | create_time = #{createTime,jdbcType=TIMESTAMP}, 112 | 113 | 114 | update_time = #{updateTime,jdbcType=TIMESTAMP}, 115 | 116 | 117 | where id = #{id,jdbcType=BIGINT} 118 | 119 | 120 | 121 | update t_role 122 | set role_no = #{roleNo,jdbcType=VARCHAR}, 123 | `name` = #{name,jdbcType=VARCHAR}, 124 | `status` = #{status,jdbcType=CHAR}, 125 | `type` = #{type,jdbcType=CHAR}, 126 | create_time = #{createTime,jdbcType=TIMESTAMP}, 127 | update_time = #{updateTime,jdbcType=TIMESTAMP} 128 | where id = #{id,jdbcType=BIGINT} 129 | 130 | 131 | 148 | 156 | 169 | 172 | 173 | -------------------------------------------------------------------------------- /src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | id, user_id, user_name, `password`, deal_password, sex, `type`, phone, mobie, email, 25 | we_chat, telegram, address, zip_code, create_time, update_time 26 | 27 | 28 | 29 | 30 | AND user_id = #{userId} 31 | 32 | 33 | AND sex = #{sex} 34 | 35 | 36 | AND create_time = ]]> #{createTime[0]} AND create_time #{createTime[1]} 37 | 38 | 39 | 40 | 46 | 47 | delete from t_user 48 | where id = #{id,jdbcType=BIGINT} 49 | 50 | 51 | insert into t_user (user_id, user_name, `password`, 52 | deal_password, sex, `type`, 53 | phone, mobie, email, 54 | we_chat, telegram, address, 55 | zip_code, create_time, update_time 56 | ) 57 | values (#{userId,jdbcType=VARCHAR}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 58 | #{dealPassword,jdbcType=VARCHAR}, #{sex,jdbcType=CHAR}, #{type,jdbcType=VARCHAR}, 59 | #{phone,jdbcType=VARCHAR}, #{mobie,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, 60 | #{weChat,jdbcType=VARCHAR}, #{telegram,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR}, 61 | #{zipCode,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP} 62 | ) 63 | 64 | 65 | 66 | SELECT LAST_INSERT_ID() as id 67 | 68 | insert into t_user 69 | 70 | 71 | user_id, 72 | 73 | 74 | user_name, 75 | 76 | 77 | `password`, 78 | 79 | 80 | deal_password, 81 | 82 | 83 | sex, 84 | 85 | 86 | `type`, 87 | 88 | 89 | phone, 90 | 91 | 92 | mobie, 93 | 94 | 95 | email, 96 | 97 | 98 | we_chat, 99 | 100 | 101 | telegram, 102 | 103 | 104 | address, 105 | 106 | 107 | zip_code, 108 | 109 | 110 | create_time, 111 | 112 | 113 | update_time, 114 | 115 | 116 | 117 | 118 | #{userId,jdbcType=VARCHAR}, 119 | 120 | 121 | #{userName,jdbcType=VARCHAR}, 122 | 123 | 124 | #{password,jdbcType=VARCHAR}, 125 | 126 | 127 | #{dealPassword,jdbcType=VARCHAR}, 128 | 129 | 130 | #{sex,jdbcType=CHAR}, 131 | 132 | 133 | #{type,jdbcType=VARCHAR}, 134 | 135 | 136 | #{phone,jdbcType=VARCHAR}, 137 | 138 | 139 | #{mobie,jdbcType=VARCHAR}, 140 | 141 | 142 | #{email,jdbcType=VARCHAR}, 143 | 144 | 145 | #{weChat,jdbcType=VARCHAR}, 146 | 147 | 148 | #{telegram,jdbcType=VARCHAR}, 149 | 150 | 151 | #{address,jdbcType=VARCHAR}, 152 | 153 | 154 | #{zipCode,jdbcType=VARCHAR}, 155 | 156 | 157 | #{createTime,jdbcType=TIMESTAMP}, 158 | 159 | 160 | #{updateTime,jdbcType=TIMESTAMP}, 161 | 162 | 163 | 164 | 165 | update t_user 166 | 167 | 168 | user_id = #{userId,jdbcType=VARCHAR}, 169 | 170 | 171 | user_name = #{userName,jdbcType=VARCHAR}, 172 | 173 | 174 | `password` = #{password,jdbcType=VARCHAR}, 175 | 176 | 177 | deal_password = #{dealPassword,jdbcType=VARCHAR}, 178 | 179 | 180 | sex = #{sex,jdbcType=CHAR}, 181 | 182 | 183 | `type` = #{type,jdbcType=VARCHAR}, 184 | 185 | 186 | phone = #{phone,jdbcType=VARCHAR}, 187 | 188 | 189 | mobie = #{mobie,jdbcType=VARCHAR}, 190 | 191 | 192 | email = #{email,jdbcType=VARCHAR}, 193 | 194 | 195 | we_chat = #{weChat,jdbcType=VARCHAR}, 196 | 197 | 198 | telegram = #{telegram,jdbcType=VARCHAR}, 199 | 200 | 201 | address = #{address,jdbcType=VARCHAR}, 202 | 203 | 204 | zip_code = #{zipCode,jdbcType=VARCHAR}, 205 | 206 | 207 | create_time = #{createTime,jdbcType=TIMESTAMP}, 208 | 209 | 210 | update_time = #{updateTime,jdbcType=TIMESTAMP}, 211 | 212 | 213 | where id = #{id,jdbcType=BIGINT} 214 | 215 | 216 | update t_user 217 | set user_id = #{userId,jdbcType=VARCHAR}, 218 | user_name = #{userName,jdbcType=VARCHAR}, 219 | `password` = #{password,jdbcType=VARCHAR}, 220 | deal_password = #{dealPassword,jdbcType=VARCHAR}, 221 | sex = #{sex,jdbcType=CHAR}, 222 | `type` = #{type,jdbcType=VARCHAR}, 223 | phone = #{phone,jdbcType=VARCHAR}, 224 | mobie = #{mobie,jdbcType=VARCHAR}, 225 | email = #{email,jdbcType=VARCHAR}, 226 | we_chat = #{weChat,jdbcType=VARCHAR}, 227 | telegram = #{telegram,jdbcType=VARCHAR}, 228 | address = #{address,jdbcType=VARCHAR}, 229 | zip_code = #{zipCode,jdbcType=VARCHAR}, 230 | create_time = #{createTime,jdbcType=TIMESTAMP}, 231 | update_time = #{updateTime,jdbcType=TIMESTAMP} 232 | where id = #{id,jdbcType=BIGINT} 233 | 234 | 235 | 252 | 253 | 262 | 263 | 279 | 280 | 291 | 292 | 293 | -------------------------------------------------------------------------------- /src/main/resources/mapper/UserRoleMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | id, user_id, role_no, create_time, update_time 13 | 14 | 20 | 21 | delete from t_user_role 22 | where id = #{id,jdbcType=BIGINT} 23 | 24 | 25 | insert into t_user_role (user_id, role_no, create_time, 26 | update_time) 27 | values (#{userId,jdbcType=VARCHAR}, #{roleNo,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, 28 | #{updateTime,jdbcType=TIMESTAMP}) 29 | 30 | 31 | insert into t_user_role 32 | 33 | 34 | user_id, 35 | 36 | 37 | role_no, 38 | 39 | 40 | create_time, 41 | 42 | 43 | update_time, 44 | 45 | 46 | 47 | 48 | #{userId,jdbcType=VARCHAR}, 49 | 50 | 51 | #{roleNo,jdbcType=VARCHAR}, 52 | 53 | 54 | #{createTime,jdbcType=TIMESTAMP}, 55 | 56 | 57 | #{updateTime,jdbcType=TIMESTAMP}, 58 | 59 | 60 | 61 | 62 | update t_user_role 63 | 64 | 65 | user_id = #{userId,jdbcType=VARCHAR}, 66 | 67 | 68 | role_no = #{roleNo,jdbcType=VARCHAR}, 69 | 70 | 71 | create_time = #{createTime,jdbcType=TIMESTAMP}, 72 | 73 | 74 | update_time = #{updateTime,jdbcType=TIMESTAMP}, 75 | 76 | 77 | where id = #{id,jdbcType=BIGINT} 78 | 79 | 80 | update t_user_role 81 | set user_id = #{userId,jdbcType=VARCHAR}, 82 | role_no = #{roleNo,jdbcType=VARCHAR}, 83 | create_time = #{createTime,jdbcType=TIMESTAMP}, 84 | update_time = #{updateTime,jdbcType=TIMESTAMP} 85 | where id = #{id,jdbcType=BIGINT} 86 | 87 | -------------------------------------------------------------------------------- /src/main/resources/mapper/admindb/AdminUserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | ID, USER_ID, USER_NAME, `PASSWORD`, DEALPASSWORD, SEX, `TYPE`, USER_LEVEL, PHONE, 29 | MOBILE, EMAIL, we_chat, telegram, ADDRESS, ZIP_CODE, ROLE_ID, STATUS_FLAG, OTHER_INFO, 30 | CREATE_TIME, LANG_TYPE, PERMISSION_LANG 31 | 32 | 38 | 39 | delete from t_admin_user 40 | where ID = #{id,jdbcType=BIGINT} 41 | 42 | 43 | insert into t_admin_user (USER_ID, USER_NAME, `PASSWORD`, 44 | DEALPASSWORD, SEX, `TYPE`, 45 | USER_LEVEL, PHONE, MOBILE, 46 | EMAIL, we_chat, telegram, 47 | ADDRESS, ZIP_CODE, ROLE_ID, 48 | STATUS_FLAG, OTHER_INFO, CREATE_TIME, 49 | LANG_TYPE, PERMISSION_LANG) 50 | values (#{userId,jdbcType=VARCHAR}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 51 | #{dealpassword,jdbcType=VARCHAR}, #{sex,jdbcType=CHAR}, #{type,jdbcType=VARCHAR}, 52 | #{userLevel,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{mobile,jdbcType=VARCHAR}, 53 | #{email,jdbcType=VARCHAR}, #{weChat,jdbcType=VARCHAR}, #{telegram,jdbcType=VARCHAR}, 54 | #{address,jdbcType=VARCHAR}, #{zipCode,jdbcType=VARCHAR}, #{roleId,jdbcType=VARCHAR}, 55 | #{statusFlag,jdbcType=CHAR}, #{otherInfo,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, 56 | #{langType,jdbcType=VARCHAR}, #{permissionLang,jdbcType=VARCHAR}) 57 | 58 | 59 | insert into t_admin_user 60 | 61 | 62 | USER_ID, 63 | 64 | 65 | USER_NAME, 66 | 67 | 68 | `PASSWORD`, 69 | 70 | 71 | DEALPASSWORD, 72 | 73 | 74 | SEX, 75 | 76 | 77 | `TYPE`, 78 | 79 | 80 | USER_LEVEL, 81 | 82 | 83 | PHONE, 84 | 85 | 86 | MOBILE, 87 | 88 | 89 | EMAIL, 90 | 91 | 92 | we_chat, 93 | 94 | 95 | telegram, 96 | 97 | 98 | ADDRESS, 99 | 100 | 101 | ZIP_CODE, 102 | 103 | 104 | ROLE_ID, 105 | 106 | 107 | STATUS_FLAG, 108 | 109 | 110 | OTHER_INFO, 111 | 112 | 113 | CREATE_TIME, 114 | 115 | 116 | LANG_TYPE, 117 | 118 | 119 | PERMISSION_LANG, 120 | 121 | 122 | 123 | 124 | #{userId,jdbcType=VARCHAR}, 125 | 126 | 127 | #{userName,jdbcType=VARCHAR}, 128 | 129 | 130 | #{password,jdbcType=VARCHAR}, 131 | 132 | 133 | #{dealpassword,jdbcType=VARCHAR}, 134 | 135 | 136 | #{sex,jdbcType=CHAR}, 137 | 138 | 139 | #{type,jdbcType=VARCHAR}, 140 | 141 | 142 | #{userLevel,jdbcType=VARCHAR}, 143 | 144 | 145 | #{phone,jdbcType=VARCHAR}, 146 | 147 | 148 | #{mobile,jdbcType=VARCHAR}, 149 | 150 | 151 | #{email,jdbcType=VARCHAR}, 152 | 153 | 154 | #{weChat,jdbcType=VARCHAR}, 155 | 156 | 157 | #{telegram,jdbcType=VARCHAR}, 158 | 159 | 160 | #{address,jdbcType=VARCHAR}, 161 | 162 | 163 | #{zipCode,jdbcType=VARCHAR}, 164 | 165 | 166 | #{roleId,jdbcType=VARCHAR}, 167 | 168 | 169 | #{statusFlag,jdbcType=CHAR}, 170 | 171 | 172 | #{otherInfo,jdbcType=VARCHAR}, 173 | 174 | 175 | #{createTime,jdbcType=TIMESTAMP}, 176 | 177 | 178 | #{langType,jdbcType=VARCHAR}, 179 | 180 | 181 | #{permissionLang,jdbcType=VARCHAR}, 182 | 183 | 184 | 185 | 186 | update t_admin_user 187 | 188 | 189 | USER_ID = #{userId,jdbcType=VARCHAR}, 190 | 191 | 192 | USER_NAME = #{userName,jdbcType=VARCHAR}, 193 | 194 | 195 | `PASSWORD` = #{password,jdbcType=VARCHAR}, 196 | 197 | 198 | DEALPASSWORD = #{dealpassword,jdbcType=VARCHAR}, 199 | 200 | 201 | SEX = #{sex,jdbcType=CHAR}, 202 | 203 | 204 | `TYPE` = #{type,jdbcType=VARCHAR}, 205 | 206 | 207 | USER_LEVEL = #{userLevel,jdbcType=VARCHAR}, 208 | 209 | 210 | PHONE = #{phone,jdbcType=VARCHAR}, 211 | 212 | 213 | MOBILE = #{mobile,jdbcType=VARCHAR}, 214 | 215 | 216 | EMAIL = #{email,jdbcType=VARCHAR}, 217 | 218 | 219 | we_chat = #{weChat,jdbcType=VARCHAR}, 220 | 221 | 222 | telegram = #{telegram,jdbcType=VARCHAR}, 223 | 224 | 225 | ADDRESS = #{address,jdbcType=VARCHAR}, 226 | 227 | 228 | ZIP_CODE = #{zipCode,jdbcType=VARCHAR}, 229 | 230 | 231 | ROLE_ID = #{roleId,jdbcType=VARCHAR}, 232 | 233 | 234 | STATUS_FLAG = #{statusFlag,jdbcType=CHAR}, 235 | 236 | 237 | OTHER_INFO = #{otherInfo,jdbcType=VARCHAR}, 238 | 239 | 240 | CREATE_TIME = #{createTime,jdbcType=TIMESTAMP}, 241 | 242 | 243 | LANG_TYPE = #{langType,jdbcType=VARCHAR}, 244 | 245 | 246 | PERMISSION_LANG = #{permissionLang,jdbcType=VARCHAR}, 247 | 248 | 249 | where ID = #{id,jdbcType=BIGINT} 250 | 251 | 252 | update t_admin_user 253 | set USER_ID = #{userId,jdbcType=VARCHAR}, 254 | USER_NAME = #{userName,jdbcType=VARCHAR}, 255 | `PASSWORD` = #{password,jdbcType=VARCHAR}, 256 | DEALPASSWORD = #{dealpassword,jdbcType=VARCHAR}, 257 | SEX = #{sex,jdbcType=CHAR}, 258 | `TYPE` = #{type,jdbcType=VARCHAR}, 259 | USER_LEVEL = #{userLevel,jdbcType=VARCHAR}, 260 | PHONE = #{phone,jdbcType=VARCHAR}, 261 | MOBILE = #{mobile,jdbcType=VARCHAR}, 262 | EMAIL = #{email,jdbcType=VARCHAR}, 263 | we_chat = #{weChat,jdbcType=VARCHAR}, 264 | telegram = #{telegram,jdbcType=VARCHAR}, 265 | ADDRESS = #{address,jdbcType=VARCHAR}, 266 | ZIP_CODE = #{zipCode,jdbcType=VARCHAR}, 267 | ROLE_ID = #{roleId,jdbcType=VARCHAR}, 268 | STATUS_FLAG = #{statusFlag,jdbcType=CHAR}, 269 | OTHER_INFO = #{otherInfo,jdbcType=VARCHAR}, 270 | CREATE_TIME = #{createTime,jdbcType=TIMESTAMP}, 271 | LANG_TYPE = #{langType,jdbcType=VARCHAR}, 272 | PERMISSION_LANG = #{permissionLang,jdbcType=VARCHAR} 273 | where ID = #{id,jdbcType=BIGINT} 274 | 275 | 276 | 287 | 288 | 304 | 305 | -------------------------------------------------------------------------------- /src/main/resources/mybatis-configuration.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/test/java/com/pkh/OpenApiApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.pkh; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class OpenApiApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/pkh/annotation/parser/ReplaceTest.java: -------------------------------------------------------------------------------- 1 | package com.pkh.annotation.parser; 2 | 3 | import com.pkh.bean.param.BaseListParam; 4 | import com.pkh.bean.param.UserListParam; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.Test; 7 | 8 | class ReplaceTest extends BaseListParam { 9 | 10 | @Test 11 | void parse() { 12 | UserListParam param = new UserListParam(" kangkang@pika.com "); 13 | Object parseObject = new ReplaceParser().parse(param); 14 | if (parseObject instanceof UserListParam) { 15 | UserListParam parseParam = (UserListParam) parseObject; 16 | Assertions.assertNotNull(parseParam); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /src/test/java/com/pkh/configuraton/PikaDayConfigurationTest.java: -------------------------------------------------------------------------------- 1 | package com.pkh.configuraton; 2 | 3 | import com.pkh.bean.param.BaseListParam; 4 | import com.pkh.dao.prop.PikaDayBean; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.junit.jupiter.api.Assertions; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | 11 | import javax.annotation.Resource; 12 | 13 | @SpringBootTest 14 | @Slf4j 15 | class PikaDayConfigurationTest extends BaseListParam { 16 | 17 | @Resource 18 | PikaConfiguration pikaDayConfiguration; 19 | 20 | @Value("${pikaday.startTime}") 21 | private long startTime; 22 | 23 | @Value("${pikaday.endTime}") 24 | private long endTime; 25 | 26 | @Test 27 | void testGetPikaDayBean() { 28 | PikaDayBean pikaDayBean = pikaDayConfiguration.getPikaDayBean(); 29 | Assertions.assertNotNull("pikaDayBean", "pikaDay配置类获取为空"); 30 | log.info(pikaDayBean.toString()); 31 | } 32 | 33 | @Test 34 | void testGetPikaDayValue() { 35 | log.info("startTime: {}, endTime:{}", startTime, endTime); 36 | } 37 | } -------------------------------------------------------------------------------- /src/test/java/com/pkh/dao/mapper/RoleMapperTest.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.mapper; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class RoleMapperTest { 8 | 9 | @Test 10 | void selectByParam() { 11 | } 12 | 13 | @Test 14 | void countByParam() { 15 | } 16 | 17 | @Test 18 | void selectByCondition() { 19 | } 20 | 21 | @Test 22 | void countByCondition() { 23 | } 24 | } -------------------------------------------------------------------------------- /src/test/java/com/pkh/dao/mapper/UserMapperTest.java: -------------------------------------------------------------------------------- 1 | package com.pkh.dao.mapper; 2 | 3 | import com.pkh.bean.param.UserListParam; 4 | import com.pkh.dao.po.User; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.Test; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | 10 | import java.util.List; 11 | 12 | @SpringBootTest 13 | class UserMapperTest { 14 | 15 | @Autowired 16 | UserMapper userMapper; 17 | 18 | @Test 19 | void selectByParam() { 20 | UserListParam param = new UserListParam(); 21 | param.setUserId("kangkang@pika.com"); 22 | List users = userMapper.selectByParam(param); 23 | Assertions.assertNotNull(users); 24 | } 25 | } -------------------------------------------------------------------------------- /src/test/java/com/pkh/service/impl/UserServiceImplTest.java: -------------------------------------------------------------------------------- 1 | package com.pkh.service.impl; 2 | 3 | import com.pkh.bean.param.UserListParam; 4 | import com.pkh.dao.mapper.UserMapper; 5 | import com.pkh.dao.po.User; 6 | import org.junit.jupiter.api.BeforeEach; 7 | import org.junit.jupiter.api.Test; 8 | 9 | import java.util.*; 10 | 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | import static org.mockito.ArgumentMatchers.any; 13 | import static org.mockito.Mockito.mock; 14 | import static org.mockito.Mockito.when; 15 | 16 | class UserServiceImplTest { 17 | 18 | private UserServiceImpl userServiceImplUnderTest; 19 | 20 | @BeforeEach 21 | void setUp() { 22 | userServiceImplUnderTest = new UserServiceImpl(); 23 | userServiceImplUnderTest.userMapper = mock(UserMapper.class); 24 | } 25 | 26 | @Test 27 | void testGetByParam() { 28 | // 构造userMapper.selectByParam()的参数 29 | final UserListParam param = new UserListParam(); 30 | param.setUserId("kangkang@pika.com"); 31 | 32 | // 构造userMapper.selectByParam()返回值 33 | final User user = new User(); 34 | user.setUserId("kangkang@pika.com"); 35 | final List users = Arrays.asList(user); 36 | when(userServiceImplUnderTest.userMapper.selectByParam(param)).thenReturn(users); 37 | 38 | // 执行userService.getByParam() 39 | final List result = userServiceImplUnderTest.getByParam(param); 40 | 41 | // 验证结果 42 | result.forEach(item -> { 43 | System.out.println(item.toString() + "\n"); 44 | }); 45 | } 46 | 47 | @Test 48 | void testGetByParam_UserMapperReturnsNoItems() { 49 | // Setup 50 | final UserListParam param = new UserListParam(); 51 | param.setUserId("kangkang@pika.com"); 52 | 53 | when(userServiceImplUnderTest.userMapper.selectByParam(new UserListParam())) 54 | .thenReturn(Collections.emptyList()); 55 | 56 | // Run the test 57 | final List result = userServiceImplUnderTest.getByParam(param); 58 | 59 | // Verify the results 60 | assertThat(result).isEqualTo(Collections.emptyList()); 61 | } 62 | 63 | @Test 64 | void testCountByParam() { 65 | // Setup 66 | final UserListParam param = new UserListParam(); 67 | param.setPageIndex(0); 68 | param.setPageSize(0); 69 | param.setOffset(0); 70 | param.setUserId("userId"); 71 | param.setSex("sex"); 72 | param.setCreateTime(Arrays.asList("value")); 73 | 74 | when(userServiceImplUnderTest.userMapper.countByParam(new UserListParam())).thenReturn(0); 75 | 76 | // Run the test 77 | final Integer result = userServiceImplUnderTest.countByParam(param); 78 | 79 | // Verify the results 80 | assertThat(result).isEqualTo(0); 81 | } 82 | 83 | @Test 84 | void testGetByCondition() { 85 | // Setup 86 | final UserListParam param = new UserListParam(); 87 | param.setPageIndex(0); 88 | param.setPageSize(0); 89 | param.setOffset(0); 90 | param.setUserId("userId"); 91 | param.setSex("sex"); 92 | param.setCreateTime(Arrays.asList("value")); 93 | 94 | // Configure UserMapper.selectByCondition(...). 95 | final User user = new User(); 96 | user.setId(0L); 97 | user.setUserId("userId"); 98 | user.setUserName("userName"); 99 | user.setPassword("password"); 100 | user.setDealPassword("dealPassword"); 101 | user.setSex("sex"); 102 | user.setType("type"); 103 | user.setPhone("phone"); 104 | user.setMobie("mobie"); 105 | user.setEmail("email"); 106 | user.setWeChat("weChat"); 107 | user.setTelegram("telegram"); 108 | user.setAddress("address"); 109 | user.setZipCode("zipCode"); 110 | user.setCreateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime()); 111 | final List users = Arrays.asList(user); 112 | when(userServiceImplUnderTest.userMapper.selectByCondition(new HashMap<>(), 0, 0)).thenReturn(users); 113 | 114 | // Run the test 115 | final List result = userServiceImplUnderTest.getByCondition(param); 116 | 117 | // Verify the results 118 | } 119 | 120 | @Test 121 | void testGetByCondition_UserMapperReturnsNoItems() { 122 | // Setup 123 | final UserListParam param = new UserListParam(); 124 | param.setPageIndex(0); 125 | param.setPageSize(0); 126 | param.setOffset(0); 127 | param.setUserId("userId"); 128 | param.setSex("sex"); 129 | param.setCreateTime(Arrays.asList("value")); 130 | 131 | when(userServiceImplUnderTest.userMapper.selectByCondition(new HashMap<>(), 0, 0)) 132 | .thenReturn(Collections.emptyList()); 133 | 134 | // Run the test 135 | final List result = userServiceImplUnderTest.getByCondition(param); 136 | 137 | // Verify the results 138 | assertThat(result).isEqualTo(Collections.emptyList()); 139 | } 140 | 141 | @Test 142 | void testCountByCondition() { 143 | // Setup 144 | final UserListParam param = new UserListParam(); 145 | param.setPageIndex(0); 146 | param.setPageSize(0); 147 | param.setOffset(0); 148 | param.setUserId("userId"); 149 | param.setSex("sex"); 150 | param.setCreateTime(Arrays.asList("value")); 151 | 152 | when(userServiceImplUnderTest.userMapper.countByCondition(new HashMap<>())).thenReturn(0); 153 | 154 | // Run the test 155 | final Integer result = userServiceImplUnderTest.countByCondition(param); 156 | 157 | // Verify the results 158 | assertThat(result).isEqualTo(0); 159 | } 160 | 161 | @Test 162 | void testAdd() { 163 | // Setup 164 | final User param = new User(); 165 | param.setId(0L); 166 | param.setUserId("userId"); 167 | param.setUserName("userName"); 168 | param.setPassword("password"); 169 | param.setDealPassword("dealPassword"); 170 | param.setSex("sex"); 171 | param.setType("type"); 172 | param.setPhone("phone"); 173 | param.setMobie("mobie"); 174 | param.setEmail("email"); 175 | param.setWeChat("weChat"); 176 | param.setTelegram("telegram"); 177 | param.setAddress("address"); 178 | param.setZipCode("zipCode"); 179 | param.setCreateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime()); 180 | 181 | when(userServiceImplUnderTest.userMapper.insertSelective(any(User.class))).thenReturn(0); 182 | 183 | // Run the test 184 | final int result = userServiceImplUnderTest.add(param); 185 | 186 | // Verify the results 187 | assertThat(result).isEqualTo(0); 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /src/test/java/com/pkh/util/HttpUtilTest.java: -------------------------------------------------------------------------------- 1 | package com.pkh.util; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.alibaba.fastjson.JSONObject; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | 11 | import java.io.UnsupportedEncodingException; 12 | import java.util.HashMap; 13 | 14 | @Slf4j 15 | @SpringBootTest 16 | class HttpUtilTest { 17 | 18 | @Value("${oa.baseUrl}") 19 | private String baseUrl; 20 | 21 | static HttpUtil httpUtil; 22 | static { 23 | httpUtil = new HttpUtil(); 24 | } 25 | 26 | @Test 27 | void testDoPost() { 28 | JSONObject param = new JSONObject(); 29 | String res = HttpUtil.doPost(baseUrl + "/user/list", param, "utf8"); 30 | Object parse = JSON.parse(res); 31 | log.info(res); 32 | } 33 | 34 | @Test 35 | void testDoGet() throws UnsupportedEncodingException { 36 | String res = HttpUtil.doGet(baseUrl + "/user/list", new HashMap<>(), new HashMap<>()); 37 | Object parse = JSON.parse(res); 38 | log.info(res); 39 | } 40 | 41 | @Test 42 | void testGetHttpClient() { 43 | CloseableHttpClient httpClient = HttpUtil.getHttpClient(); 44 | System.out.println(httpClient.toString()); 45 | } 46 | } 47 | --------------------------------------------------------------------------------