常用POM
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.12.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>hospital</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hospital</name>
<description>hospital</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.22</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.3.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.3.Final</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.16</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.9</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
常用工具
代码快速生成
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
public class CodeGenerator {
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/SpringBoot_10_mybatis-plus/src/main/java");
gc.setFileOverride(true);
gc.setOpen(false);
gc.setAuthor("LIFEILIN");
gc.setIdType(IdType.AUTO);
gc.setBaseResultMap(true);
gc.setBaseColumnList(true);
gc.setServiceName("%sService");
gc.setDateType(DateType.ONLY_DATE);
mpg.setGlobalConfig(gc);
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://IP:端口/数据库名?useSSL=false&createDatabaseIfNotExist=true&serverTimezone=UTC&characterEncoding=utf8&allowPublicKeyRetrieval=false");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("javaee2021");
mpg.setDataSource(dsc);
PackageConfig pc = new PackageConfig();
pc.setParent("com.example");
pc.setMapper("mapper");
pc.setXml("mapper.xml");
pc.setEntity("pojo");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setController("controller");
mpg.setPackageInfo(pc);
StrategyConfig sc = new StrategyConfig();
sc.setNaming(NamingStrategy.underline_to_camel);
sc.setColumnNaming(NamingStrategy.underline_to_camel);
sc.setEntityLombokModel(true);
sc.setRestControllerStyle(true);
sc.setControllerMappingHyphenStyle(true);
sc.setLogicDeleteFieldName("deleted");
TableFill gmt_create = new TableFill("create_time", FieldFill.INSERT);
TableFill gmt_modified = new TableFill("update_time", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills=new ArrayList<>();
tableFills.add(gmt_create);
tableFills.add(gmt_modified);
sc.setTableFillList(tableFills);
sc.setVersionFieldName("version");
sc.setRestControllerStyle(true);
sc.setInclude("数据表名称");
mpg.setStrategy(sc);
mpg.execute();
}
}
公共工具
import com.example.hospital.config.exception.BaseErrorEnum;
import com.example.hospital.config.exception.BusinessException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Component
public class CommonUtil {
private static final String X_ACCESS_TOKEN = "X-AQI-Token";
public String getUserName() throws Exception {
String userName = (String) JwtUtil.parseJWT(gainToken()).get("username");
if (userName == null) {
throw new BusinessException(BaseErrorEnum.NOTLOGGED_IN);
}
return userName;
}
public String getRole() throws Exception {
String role = (String) JwtUtil.parseJWT(gainToken()).get("role");
if (role == null) {
throw new BusinessException(BaseErrorEnum.NOTLOGGED_IN);
}
return role;
}
public static String gainToken() {
HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
String token = request.getParameter(X_ACCESS_TOKEN);
if (token == null) {
token = request.getHeader(X_ACCESS_TOKEN);
}
return token;
}
public static Field[] getAllFields(Object object) {
Class<?> clazz = object.getClass();
List<Field> fieldList = new ArrayList<>();
while (clazz != null) {
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
clazz = clazz.getSuperclass();
}
Field[] fields = new Field[fieldList.size()];
fieldList.toArray(fields);
return fields;
}
}
JWT工具
import com.example.hospital.config.exception.BaseErrorEnum;
import com.example.hospital.config.exception.BusinessException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;
@Slf4j
public class JwtUtil {
public static final Long JWT_TTL = 24 * 60 * 60 *1000L;
public static final String JWT_KEY = "AQI";
public static String getUUID(){
String token = UUID.randomUUID().toString().replaceAll("-", "");
return token;
}
private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
SecretKey secretKey = generalKey();
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
if(ttlMillis==null){
ttlMillis=JwtUtil.JWT_TTL;
}
long expMillis = nowMillis + ttlMillis;
Date expDate = new Date(expMillis);
return Jwts.builder()
.setId(uuid)
.setSubject(subject)
.setIssuer("system")
.setIssuedAt(new Date())
.signWith(signatureAlgorithm, secretKey)
.setExpiration(expDate);
}
private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid, Map<String,Object> info) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
SecretKey secretKey = generalKey();
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
if(ttlMillis==null){
ttlMillis=JwtUtil.JWT_TTL;
}
long expMillis = nowMillis + ttlMillis;
Date expDate = new Date(expMillis);
return Jwts.builder()
.setId(uuid)
.setClaims(info)
.setSubject(subject)
.setIssuer("sg")
.setIssuedAt(now)
.signWith(signatureAlgorithm, secretKey)
.setExpiration(expDate);
}
public static String createJWT(String id, String subject, Long ttlMillis) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);
return builder.compact();
}
public static String createJWT(String subject) {
JwtBuilder builder = getJwtBuilder(subject, null, getUUID());
return builder.compact();
}
public static String createJWT(String subject, Long ttlMillis) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());
return builder.compact();
}
public static String createJWT(String subject, Long ttlMillis,Map<String ,Object> info) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID(),info);
return builder.compact();
}
public static Claims parseJWT(String jwt) throws Exception {
try {
SecretKey secretKey = generalKey();
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(jwt)
.getBody();
}catch (Exception e){
log.info(e.getMessage());
}
throw new BusinessException(BaseErrorEnum.TOKEN_VERIFICATION_ERROR);
}
public static boolean isExpiration(String token) {
try {
return parseJWT(token).getExpiration().before(new Date());
} catch (Exception e) {
return true;
}
}
public static SecretKey generalKey() {
byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
public static void main(String[] args) throws Exception {
Map<String,Object> info = new HashMap<>();
info.put("roles","admin");
String token = createJWT("test",JWT_TTL,info);
System.out.println(token);
Claims claims = parseJWT(token);
System.out.println(claims.get("roles"));
}
}
Redis工具
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
private StringRedisTemplate redisTemplate;
public void setRedisTemplate(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public StringRedisTemplate getRedisTemplate() {
return this.redisTemplate;
}
public void delete(String key) {
redisTemplate.delete(key);
}
public void delete(Collection<String> keys) {
redisTemplate.delete(keys);
}
public byte[] dump(String key) {
return redisTemplate.dump(key);
}
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
public Boolean expire(String key, long timeout, TimeUnit unit) {
return redisTemplate.expire(key, timeout, unit);
}
public Boolean expireAt(String key, Date date) {
return redisTemplate.expireAt(key, date);
}
public Set<String> keys(String pattern) {
return redisTemplate.keys(pattern);
}
public Boolean move(String key, int dbIndex) {
return redisTemplate.move(key, dbIndex);
}
public Boolean persist(String key) {
return redisTemplate.persist(key);
}
public Long getExpire(String key, TimeUnit unit) {
return redisTemplate.getExpire(key, unit);
}
public Long getExpire(String key) {
return redisTemplate.getExpire(key);
}
public String randomKey() {
return redisTemplate.randomKey();
}
public void rename(String oldKey, String newKey) {
redisTemplate.rename(oldKey, newKey);
}
public Boolean renameIfAbsent(String oldKey, String newKey) {
return redisTemplate.renameIfAbsent(oldKey, newKey);
}
public DataType type(String key) {
return redisTemplate.type(key);
}
public void set(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
public String get(String key) {
return redisTemplate.opsForValue().get(key);
}
public String getRange(String key, long start, long end) {
return redisTemplate.opsForValue().get(key, start, end);
}
public String getAndSet(String key, String value) {
return redisTemplate.opsForValue().getAndSet(key, value);
}
public Boolean getBit(String key, long offset) {
return redisTemplate.opsForValue().getBit(key, offset);
}
public List<String> multiGet(Collection<String> keys) {
return redisTemplate.opsForValue().multiGet(keys);
}
public boolean setBit(String key, long offset, boolean value) {
return redisTemplate.opsForValue().setBit(key, offset, value);
}
public void setEx(String key, String value, long timeout, TimeUnit unit) {
redisTemplate.opsForValue().set(key, value, timeout, unit);
}
public boolean setIfAbsent(String key, String value) {
return redisTemplate.opsForValue().setIfAbsent(key, value);
}
public void setRange(String key, String value, long offset) {
redisTemplate.opsForValue().set(key, value, offset);
}
public Long size(String key) {
return redisTemplate.opsForValue().size(key);
}
public void multiSet(Map<String, String> maps) {
redisTemplate.opsForValue().multiSet(maps);
}
public boolean multiSetIfAbsent(Map<String, String> maps) {
return redisTemplate.opsForValue().multiSetIfAbsent(maps);
}
public Long incrBy(String key, long increment) {
return redisTemplate.opsForValue().increment(key, increment);
}
public Double incrByFloat(String key, double increment) {
return redisTemplate.opsForValue().increment(key, increment);
}
public Integer append(String key, String value) {
return redisTemplate.opsForValue().append(key, value);
}
public Object hGet(String key, String field) {
return redisTemplate.opsForHash().get(key, field);
}
public Map<Object, Object> hGetAll(String key) {
return redisTemplate.opsForHash().entries(key);
}
public List<Object> hMultiGet(String key, Collection<Object> fields) {
return redisTemplate.opsForHash().multiGet(key, fields);
}
public void hPut(String key, String hashKey, String value) {
redisTemplate.opsForHash().put(key, hashKey, value);
}
public void hPutAll(String key, Map<String, String> maps) {
redisTemplate.opsForHash().putAll(key, maps);
}
public Boolean hPutIfAbsent(String key, String hashKey, String value) {
return redisTemplate.opsForHash().putIfAbsent(key, hashKey, value);
}
public Long hDelete(String key, Object... fields) {
return redisTemplate.opsForHash().delete(key, fields);
}
public boolean hExists(String key, String field) {
return redisTemplate.opsForHash().hasKey(key, field);
}
public Long hIncrBy(String key, Object field, long increment) {
return redisTemplate.opsForHash().increment(key, field, increment);
}
public Double hIncrByFloat(String key, Object field, double delta) {
return redisTemplate.opsForHash().increment(key, field, delta);
}
public Set<Object> hKeys(String key) {
return redisTemplate.opsForHash().keys(key);
}
public Long hSize(String key) {
return redisTemplate.opsForHash().size(key);
}
public List<Object> hValues(String key) {
return redisTemplate.opsForHash().values(key);
}
public Cursor<Entry<Object, Object>> hScan(String key, ScanOptions options) {
return redisTemplate.opsForHash().scan(key, options);
}
public String lIndex(String key, long index) {
return redisTemplate.opsForList().index(key, index);
}
public List<String> lRange(String key, long start, long end) {
return redisTemplate.opsForList().range(key, start, end);
}
public Long lLeftPush(String key, String value) {
return redisTemplate.opsForList().leftPush(key, value);
}
public Long lLeftPushAll(String key, String... value) {
return redisTemplate.opsForList().leftPushAll(key, value);
}
public Long lLeftPushAll(String key, Collection<String> value) {
return redisTemplate.opsForList().leftPushAll(key, value);
}
public Long lLeftPushIfPresent(String key, String value) {
return redisTemplate.opsForList().leftPushIfPresent(key, value);
}
public Long lLeftPush(String key, String pivot, String value) {
return redisTemplate.opsForList().leftPush(key, pivot, value);
}
public Long lRightPush(String key, String value) {
return redisTemplate.opsForList().rightPush(key, value);
}
public Long lRightPushAll(String key, String... value) {
return redisTemplate.opsForList().rightPushAll(key, value);
}
public Long lRightPushAll(String key, Collection<String> value) {
return redisTemplate.opsForList().rightPushAll(key, value);
}
public Long lRightPushIfPresent(String key, String value) {
return redisTemplate.opsForList().rightPushIfPresent(key, value);
}
public Long lRightPush(String key, String pivot, String value) {
return redisTemplate.opsForList().rightPush(key, pivot, value);
}
public void lSet(String key, long index, String value) {
redisTemplate.opsForList().set(key, index, value);
}
public String lLeftPop(String key) {
return redisTemplate.opsForList().leftPop(key);
}
public String lBLeftPop(String key, long timeout, TimeUnit unit) {
return redisTemplate.opsForList().leftPop(key, timeout, unit);
}
public String lRightPop(String key) {
return redisTemplate.opsForList().rightPop(key);
}
public String lBRightPop(String key, long timeout, TimeUnit unit) {
return redisTemplate.opsForList().rightPop(key, timeout, unit);
}
public String lRightPopAndLeftPush(String sourceKey, String destinationKey) {
return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey,
destinationKey);
}
public String lBRightPopAndLeftPush(String sourceKey, String destinationKey,
long timeout, TimeUnit unit) {
return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey,
destinationKey, timeout, unit);
}
public Long lRemove(String key, long index, String value) {
return redisTemplate.opsForList().remove(key, index, value);
}
public void lTrim(String key, long start, long end) {
redisTemplate.opsForList().trim(key, start, end);
}
public Long lLen(String key) {
return redisTemplate.opsForList().size(key);
}
public Long sAdd(String key, String... values) {
return redisTemplate.opsForSet().add(key, values);
}
public Long sRemove(String key, Object... values) {
return redisTemplate.opsForSet().remove(key, values);
}
public String sPop(String key) {
return redisTemplate.opsForSet().pop(key);
}
public Boolean sMove(String key, String value, String destKey) {
return redisTemplate.opsForSet().move(key, value, destKey);
}
public Long sSize(String key) {
return redisTemplate.opsForSet().size(key);
}
public Boolean sIsMember(String key, Object value) {
return redisTemplate.opsForSet().isMember(key, value);
}
public Set<String> sIntersect(String key, String otherKey) {
return redisTemplate.opsForSet().intersect(key, otherKey);
}
public Set<String> sIntersect(String key, Collection<String> otherKeys) {
return redisTemplate.opsForSet().intersect(key, otherKeys);
}
public Long sIntersectAndStore(String key, String otherKey, String destKey) {
return redisTemplate.opsForSet().intersectAndStore(key, otherKey,
destKey);
}
public Long sIntersectAndStore(String key, Collection<String> otherKeys,
String destKey) {
return redisTemplate.opsForSet().intersectAndStore(key, otherKeys,
destKey);
}
public Set<String> sUnion(String key, String otherKeys) {
return redisTemplate.opsForSet().union(key, otherKeys);
}
public Set<String> sUnion(String key, Collection<String> otherKeys) {
return redisTemplate.opsForSet().union(key, otherKeys);
}
public Long sUnionAndStore(String key, String otherKey, String destKey) {
return redisTemplate.opsForSet().unionAndStore(key, otherKey, destKey);
}
public Long sUnionAndStore(String key, Collection<String> otherKeys,
String destKey) {
return redisTemplate.opsForSet().unionAndStore(key, otherKeys, destKey);
}
public Set<String> sDifference(String key, String otherKey) {
return redisTemplate.opsForSet().difference(key, otherKey);
}
public Set<String> sDifference(String key, Collection<String> otherKeys) {
return redisTemplate.opsForSet().difference(key, otherKeys);
}
public Long sDifference(String key, String otherKey, String destKey) {
return redisTemplate.opsForSet().differenceAndStore(key, otherKey,
destKey);
}
public Long sDifference(String key, Collection<String> otherKeys,
String destKey) {
return redisTemplate.opsForSet().differenceAndStore(key, otherKeys,
destKey);
}
public Set<String> setMembers(String key) {
return redisTemplate.opsForSet().members(key);
}
public String sRandomMember(String key) {
return redisTemplate.opsForSet().randomMember(key);
}
public List<String> sRandomMembers(String key, long count) {
return redisTemplate.opsForSet().randomMembers(key, count);
}
public Set<String> sDistinctRandomMembers(String key, long count) {
return redisTemplate.opsForSet().distinctRandomMembers(key, count);
}
public Cursor<String> sScan(String key, ScanOptions options) {
return redisTemplate.opsForSet().scan(key, options);
}
public Boolean zAdd(String key, String value, double score) {
return redisTemplate.opsForZSet().add(key, value, score);
}
public Long zAdd(String key, Set<TypedTuple<String>> values) {
return redisTemplate.opsForZSet().add(key, values);
}
public Long zRemove(String key, Object... values) {
return redisTemplate.opsForZSet().remove(key, values);
}
public Double zIncrementScore(String key, String value, double delta) {
return redisTemplate.opsForZSet().incrementScore(key, value, delta);
}
public Long zRank(String key, Object value) {
return redisTemplate.opsForZSet().rank(key, value);
}
public Long zReverseRank(String key, Object value) {
return redisTemplate.opsForZSet().reverseRank(key, value);
}
public Set<String> zRange(String key, long start, long end) {
return redisTemplate.opsForZSet().range(key, start, end);
}
public Set<TypedTuple<String>> zRangeWithScores(String key, long start,
long end) {
return redisTemplate.opsForZSet().rangeWithScores(key, start, end);
}
public Set<String> zRangeByScore(String key, double min, double max) {
return redisTemplate.opsForZSet().rangeByScore(key, min, max);
}
public Set<TypedTuple<String>> zRangeByScoreWithScores(String key,
double min, double max) {
return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max);
}
public Set<TypedTuple<String>> zRangeByScoreWithScores(String key,
double min, double max, long start, long end) {
return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max,
start, end);
}
public Set<String> zReverseRange(String key, long start, long end) {
return redisTemplate.opsForZSet().reverseRange(key, start, end);
}
public Set<TypedTuple<String>> zReverseRangeWithScores(String key,
long start, long end) {
return redisTemplate.opsForZSet().reverseRangeWithScores(key, start,
end);
}
public Set<String> zReverseRangeByScore(String key, double min,
double max) {
return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max);
}
public Set<TypedTuple<String>> zReverseRangeByScoreWithScores(
String key, double min, double max) {
return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key,
min, max);
}
public Set<String> zReverseRangeByScore(String key, double min,
double max, long start, long end) {
return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max,
start, end);
}
public Long zCount(String key, double min, double max) {
return redisTemplate.opsForZSet().count(key, min, max);
}
public Long zSize(String key) {
return redisTemplate.opsForZSet().size(key);
}
public Long zZCard(String key) {
return redisTemplate.opsForZSet().zCard(key);
}
public Double zScore(String key, Object value) {
return redisTemplate.opsForZSet().score(key, value);
}
public Long zRemoveRange(String key, long start, long end) {
return redisTemplate.opsForZSet().removeRange(key, start, end);
}
public Long zRemoveRangeByScore(String key, double min, double max) {
return redisTemplate.opsForZSet().removeRangeByScore(key, min, max);
}
public Long zUnionAndStore(String key, String otherKey, String destKey) {
return redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey);
}
public Long zUnionAndStore(String key, Collection<String> otherKeys,
String destKey) {
return redisTemplate.opsForZSet()
.unionAndStore(key, otherKeys, destKey);
}
public Long zIntersectAndStore(String key, String otherKey,
String destKey) {
return redisTemplate.opsForZSet().intersectAndStore(key, otherKey,
destKey);
}
public Long zIntersectAndStore(String key, Collection<String> otherKeys,
String destKey) {
return redisTemplate.opsForZSet().intersectAndStore(key, otherKeys,
destKey);
}
public Cursor<TypedTuple<String>> zScan(String key, ScanOptions options) {
return redisTemplate.opsForZSet().scan(key, options);
}
}
常用配置
认证授权AOP配置
注解
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Authentication {
boolean isCertification() default true;
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Authorization {
/**
* 角色信息
*
* @return 01:管理员-admin
* 02:公众监督员-user
* 03:网格员-gridman
* 默认为所有都可以通过
*/
String role() default "";
}
AOP拦截
import com.example.hospital.config.aspect.annotation.Authentication;
import com.example.hospital.config.exception.BaseErrorEnum;
import com.example.hospital.config.exception.BusinessException;
import com.example.hospital.util.CommonUtil;
import com.example.hospital.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect
@Slf4j
@Component("AuthenticationAspect")
@Order(1)
public class AuthenticationAspect {
@Pointcut("@within(com.example.hospital.config.aspect.annotation.Authentication) || @annotation(com.example.hospital.config.aspect.annotation.Authentication)")
public void excudeService() {
}
@Around("excudeService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
Class<?> target = pjp.getTarget().getClass();
Signature signature = pjp.getSignature();
MethodSignature mSignature = (MethodSignature) signature;
Method targetMethod = target.getDeclaredMethod(mSignature.getName(), mSignature.getParameterTypes());
Boolean permit = false;
try {
Authentication authenticationClass = target.getAnnotation(Authentication.class);
permit = authenticationClass.isCertification();
} catch (Exception e) {
log.info("类上无该注解!");
}
try {
Authentication authenticationMethmod = targetMethod.getAnnotation(Authentication.class);
permit = authenticationMethmod.isCertification();
} catch (Exception e) {
log.info("方法上无该注解!");
}
if (permit) {
String token = CommonUtil.gainToken();
if (token == null)
throw new BusinessException(BaseErrorEnum.NOTLOGGED_IN);
Claims claims = JwtUtil.parseJWT(CommonUtil.gainToken());
String username = (String) claims.get("username");
if (username == null || username.equals("")) {
throw new BusinessException(BaseErrorEnum.NOTLOGGED_IN);
}
String role = (String) claims.get("role");
if (role == null || role.equals("")) {
throw new BusinessException(BaseErrorEnum.NOTLOGGED_IN);
}
}
Object result = pjp.proceed();
return result;
}
}
import com.example.hospital.config.aspect.annotation.Authorization;
import com.example.hospital.config.exception.BaseErrorEnum;
import com.example.hospital.config.exception.BusinessException;
import com.example.hospital.util.CommonUtil;
import com.example.hospital.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect
@Slf4j
@Component("AuthorizationAspect")
@Order(2)
public class AuthorizationAspect {
@Pointcut("@within(com.example.hospital.config.aspect.annotation.Authorization) || @annotation(com.example.hospital.config.aspect.annotation.Authorization)")
public void excudeService() {
}
@Around("excudeService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
Class<?> target = pjp.getTarget().getClass();
Signature signature = pjp.getSignature();
MethodSignature mSignature= (MethodSignature)signature;
Method targetMethod= target.getDeclaredMethod( mSignature.getName(), mSignature.getParameterTypes() );
String roleAnnotation = null;
try {
Authorization authenticationClass = target.getAnnotation(Authorization.class);
roleAnnotation = authenticationClass.role();
} catch ( Exception e ) {
log.info("类上无该注解!");
}
try {
Authorization authenticationMethmod= targetMethod.getAnnotation( Authorization.class );
roleAnnotation = authenticationMethmod.role();
} catch ( Exception e ) {
log.info("方法上无该注解!");
}
if ( !"".equals( roleAnnotation ) ) {
Claims claims = JwtUtil.parseJWT(CommonUtil.gainToken());
String username = (String) claims.get("username");
String role = (String) claims.get("role");
}
Object result = pjp.proceed();
return result;
}
}
异常统一配置
import lombok.Getter;
@Getter
public enum BaseErrorEnum {
ACCOUNT_ERROR("100", "不存在该用户"),
PASSWORD_ERROR("101", "密码错误"),
VERIFICATION_CODE_ERROR("102", "验证码错误"),
TOKEN_VERIFICATION_ERROR("103", "token验证失败"),
NO_PERMISSIONS("104", "无权限"),
ACCOUNT_ALREADY_EXISTS ("105", "该账号已存在,请重新输入"),
MOBILE_ALREADY_EXISTS("106", "该手机已被注册,请重新输入"),
EMAIL_ALREADY_EXISTS("107", "该邮箱已被注册,请重新输入"),
NOTLOGGED_IN("108","未登陆,请先登陆"),
BEING_TAMPERED_WITH("109", "token被篡改,无权限访问此接口!"),
BAN_USER("110", "账号已冻结,请联系管理员"),
MI_NAME_REPEAT("111", "昵称已被使用,请进行修改"),
GET_USER_FAILED("112", "获取用户信息失败"),
OTHER_ERROR("113", "其他错误"),
GET_FILE_FAILED("114", "读取文件失败"),
TOKEN_ERROR("50100", "token已过期");
private String code;
private String msg;
BaseErrorEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
public static String getMsy(String code) {
for (BaseErrorEnum e : values()) {
if (e.getCode().equals(code)) {
return e.getMsg();
}
}
return "";
}
}
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@Getter
@Setter
@Slf4j
public class BusinessException extends RuntimeException {
private String message;
private String code;
public BusinessException(String message){
this.message = message;
}
public BusinessException(BaseErrorEnum errorCode) {
this.message = errorCode.getMsg();
this.code = errorCode.getCode();
}
}
package com.example.hospital.config.exception;
import cn.hutool.core.util.StrUtil;
import com.example.hospital.config.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
@Slf4j
public class ExceptionHandler {
@org.springframework.web.bind.annotation.ExceptionHandler(BusinessException.class)
public Result<String> exceptionAll(BusinessException e) {
Result result = new Result<String>();
if (StrUtil.isNotBlank(e.getCode()))
result.setCode(Integer.parseInt(e.getCode()));
else
result.setCode(Integer.parseInt(BaseErrorEnum.OTHER_ERROR.getCode()));
result.setResult(e.getMessage());
result.setSuccess(false);
log.error("全局异常捕获,报错:{}", e.getMessage());
return result;
}
}
返回值统一
import com.example.hospital.model.CommonConstant;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.io.Serializable;
@Data
public class Result<T> implements Serializable {
private static final long serialVersionUID = 1L;
private boolean success = true;
private String message = "";
private Integer code = 0;
private T result;
private long timestamp = System.currentTimeMillis();
public Result() {
}
public Result(Integer code, String message) {
this.code = code;
this.message = message;
}
public Result<T> success(String message) {
this.message = message;
this.code = CommonConstant.SC_OK_200;
this.success = true;
return this;
}
public static<T> Result<T> ok() {
Result<T> r = new Result<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
return r;
}
public static<T> Result<T> ok(String msg) {
Result<T> r = new Result<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setResult((T) msg);
r.setMessage(msg);
return r;
}
public static<T> Result<T> ok(T data) {
Result<T> r = new Result<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setResult(data);
return r;
}
public static<T> Result<T> OK() {
Result<T> r = new Result<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
return r;
}
public static<T> Result<T> OK(String msg) {
Result<T> r = new Result<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setMessage(msg);
r.setResult((T) msg);
return r;
}
public static<T> Result<T> OKNotMes(String msg) {
Result<T> r = new Result<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setResult((T) msg);
return r;
}
public static<T> Result<T> OK(T data) {
Result<T> r = new Result<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setResult(data);
return r;
}
public static<T> Result<T> OK(String msg, T data) {
Result<T> r = new Result<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setMessage(msg);
r.setResult(data);
return r;
}
public static<T> Result<T> error(String msg, T data) {
Result<T> r = new Result<T>();
r.setSuccess(false);
r.setCode(CommonConstant.SC_INTERNAL_SERVER_ERROR_500);
r.setMessage(msg);
r.setResult(data);
return r;
}
public static<T> Result<T> error(String msg) {
return error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500, msg);
}
public static<T> Result<T> error(int code, String msg) {
Result<T> r = new Result<T>();
r.setCode(code);
r.setMessage(msg);
r.setSuccess(false);
return r;
}
public Result<T> error500(String message) {
this.message = message;
this.code = CommonConstant.SC_INTERNAL_SERVER_ERROR_500;
this.success = false;
return this;
}
public static<T> Result<T> noauth(String msg) {
return error(CommonConstant.SC_NO_AUTHZ, msg);
}
@JsonIgnore
private String onlTable;
}
Knife4j配置
package com.example.hospital.config;
import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
@Slf4j
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {
private String basePackage = "com.example.hospital.controller";
private String groupName = "product";
private String host = "http://java.tedu.cn";
private String title = "标题";
private String description = "简介";
private String termsOfServiceUrl = "服务条款URL";
private String contactName = "联系人";
private String contactUrl = "http://java.tedu.cn";
private String contactEmail = "java@tedu.cn";
private String version = "1.0.0";
@Autowired
private OpenApiExtensionResolver openApiExtensionResolver;
public Knife4jConfiguration() {
log.debug("创建配置类对象:Knife4jConfiguration");
}
@Bean
public Docket docket() {
String groupName = "1.0.0";
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.host(host)
.apiInfo(apiInfo())
.groupName(groupName)
.select()
.apis(RequestHandlerSelectors.basePackage(basePackage))
.paths(PathSelectors.any())
.build()
.extensions(openApiExtensionResolver.buildExtensions(groupName));
return docket;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title)
.description(description)
.termsOfServiceUrl(termsOfServiceUrl)
.contact(new Contact(contactName, contactUrl, contactEmail))
.version(version)
.build();
}
}
跨域配置
package com.example.hospital.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Collections;
@Configuration
public class CorsConfiguration implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("*")
.maxAge(3600);
}
@Bean
public CorsFilter corsFilter() {
org.springframework.web.cors.CorsConfiguration corsConfiguration = new org.springframework.web.cors.CorsConfiguration();
corsConfiguration.setAllowedOrigins(Collections.singletonList("*"));
corsConfiguration.addAllowedHeader(org.springframework.web.cors.CorsConfiguration.ALL);
corsConfiguration.addAllowedMethod(org.springframework.web.cors.CorsConfiguration.ALL);
corsConfiguration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
Mybatis配置
import com.neus.entity.User;
import com.neus.service.impl.UserServiceImpl;
import com.neus.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod.ParamMap;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.Properties;
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {
@Autowired
@Lazy
private UserServiceImpl userService;
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
String sqlId = mappedStatement.getId();
log.debug("------sqlId------" + sqlId);
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
Object parameter = invocation.getArgs()[1];
log.debug("------sqlCommandType------" + sqlCommandType);
String user;
try {
user = userService.lambdaQuery().eq(User::getUsername, new CommonUtil().getUserName()).one().getUsername();
}catch (Exception e) {
user = "admin";
}
if (parameter == null || user == null) {
return invocation.proceed();
}
if (SqlCommandType.INSERT == sqlCommandType) {
Field[] fields = CommonUtil.getAllFields(parameter);
for (Field field : fields) {
log.debug("------field.name------" + field.getName());
try {
if ("createBy".equals(field.getName())) {
field.setAccessible(true);
Object localCreateBy = field.get(parameter);
if (localCreateBy == null || "".equals(localCreateBy)) {
field.set(parameter, user );
}
field.setAccessible(false);
}
if ("createTime".equals(field.getName())) {
field.setAccessible(true);
Object localCreateDate = field.get(parameter);
if (localCreateDate == null || "".equals(localCreateDate)) {
field.set(parameter, new Date());
}
field.setAccessible(false);
}
if ("updateBy".equals(field.getName())) {
field.setAccessible(true);
field.set(parameter, user );
field.setAccessible(false);
}
if ("updateTime".equals(field.getName())) {
field.setAccessible(true);
field.set(parameter, new Date());
field.setAccessible(false);
}
} catch (Exception e) {
}
}
}
if (SqlCommandType.UPDATE == sqlCommandType) {
Field[] fields = null;
if (parameter instanceof ParamMap) {
ParamMap<?> p = (ParamMap<?>) parameter;
String et = "et";
if (p.containsKey(et)) {
parameter = p.get("param1");
} else {
parameter = p.get("param2");
}
if (parameter == null) {
return invocation.proceed();
}
fields = CommonUtil.getAllFields(parameter);
} else {
fields = CommonUtil.getAllFields(parameter);
}
for (Field field : fields) {
log.debug("------field.name------" + field.getName());
try {
if ("updateBy".equals( field.getName())) {
if (user != null) {
field.setAccessible(true);
field.set(parameter, user);
field.setAccessible(false);
}
}
if ("updateTime".equals(field.getName())) {
field.setAccessible(true);
field.set(parameter, new Date());
field.setAccessible(false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
Redis配置
package com.example.hospital.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig{
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
YML配置
spring:
redis:
database: 0
host: ip
port: 端口
timeout: 5000
servlet:
multipart:
enabled: true
max-file-size: 800MB
max-request-size: 800MB
application:
name: hospital
datasource:
url: jdbc:mysql://ip:端口/数据库名称?useSSL=false&createDatabaseIfNotExist=true&serverTimezone=UTC&characterEncoding=utf8&allowPublicKeyRetrieval=false
username: root
password: javaee2021
driver-class-name: com.mysql.cj.jdbc.Driver
knife4j:
enable: true
server:
port: 9999