1.redis?
这个项目用数据库存储用户的注册,登录数据,确保用户可以登录,和成功注册。
用redis短期存储用户的在线状态,保持用户的在线状态。即在用户登录期间(redis信息不过期)情况下,可以得到用户的状态信息。只要用户登录,或者注册成功,它们的信息就会通过JWT加密后放到redis中
2.jwt
一种加密技术,目前也不太清楚,这是JWT工具类,对用户信息进行加密,这样从redis获取的信息便是加密过的用户信息。
public class JWTUtils {
private static final String jwtToken = "123456Mszlu!@#$$";
public static String createToken(Long userId){
Map<String,Object> claims = new HashMap<>();
claims.put("userId",userId);
JwtBuilder jwtBuilder = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, jwtToken) // 签发算法,秘钥为jwtToken
.setClaims(claims) // body数据,要唯一,自行设置
.setIssuedAt(new Date()) // 设置签发时间
.setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 60 * 1000));// 一天的有效时间
String token = jwtBuilder.compact();
return token;
}
//用户验证,看看内部是否存在
public static Map<String, Object> checkToken(String token){
try {
Jwt parse = Jwts.parser().setSigningKey(jwtToken).parse(token);
return (Map<String, Object>) parse.getBody();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
3.多线程,线程池
更改数据库时,会加入写锁,在读取数据库时需要等锁解掉才能执行下一步,为了节省时间,也为防止更改出错造成下一步无法执行,采用多线程操作,读取数据库和更改数据库做到同时操作,非常给力。
4.mp框架
4.1用mp框架进行更新时,确保后端映射对象的类型为非引用类型
以免出现进行更新操作时的BUG
如下
//错误示范
int count;
//正确示范
Integer count;
这两者有区别,int类型默认初始值为0;Integer默认的初始值为null,在用mybatis-plus进行更新操作时,方法如下
public void updataArticleViewCount(ArticleMapper articleMapper, Article article) {
Article articleUpdate = new Article();
articleUpdate.setViewCounts(article.getViewCounts() + 1);
//MP的知识,得去学啊
LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Article::getId,article.getId());
queryWrapper.eq(Article::getViewCounts,article.getViewCounts());
//等价于
// UPDATE ms_article SET comment_counts=?, view_counts=?, weight=? WHERE (id = ? AND view_counts = ?)
articleMapper.update(articleUpdate,queryWrapper);
try {
//睡眠5秒 证明不会影响主线程的使用
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
这里我本意只是想让变量getViewCounts +1,但我article对象和articleVo对象内属性类型有引用类型int,他的初始值是0,这一波操作把要操作的对象属性为引用类型的值全变成0,非常痛苦。
等价的MYSQL语句为
UPDATE ms_article SET comment_counts=?, view_counts=?, weight=? WHERE (id = ? AND view_counts = ?)
将引用类型的参数全更新成0了,这可不行
将参数全改成非引用类型Integer,如下所示
package com.mzlu.blog.dao.pojo;
import lombok.Data;
@Data
public class Article {
public static final int Article_TOP = 1;
public static final int Article_Common = 0;
private Long id;
private String title;
private String summary;
private Integer commentCounts;
private Integer viewCounts;
/**
* 作者id
*/
private Long authorId;
/**
* 内容id
*/
private Long bodyId;
/**
*类别id
*/
private Long categoryId;
/**
* 置顶
*/
private Integer weight;
/**
* 创建时间
*/
private Long createDate;
}
类代码
package com.mzlu.blog.vo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.util.List;
@Data
public class ArticleVo {
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
private String title;
private String summary;
private Integer commentCounts;
private Integer viewCounts;
private Integer weight;
/**
* 创建时间
*/
private String createDate;
private String author;
private ArticleBodyVo body;
private List<TagVo> tags;
private CategoryVo category;
}
这样它们的初始值便是null,在mp框架进行操作时,不会对这些属性进行更新
等价SQL语句变成
UPDATE ms_article SET view_counts=? WHERE (id = ? AND view_counts = ?)
这样子就做到了只对指定属性进行更新了
4.2?LambdaQueryWrapper工具
后续再总结
5.AOP
这里用到@Aspect注解
嘴巴说不定清,上代码体会一下
设置日志注解
package com.mzlu.blog.common.aop;
import java.lang.annotation.*;
/**
* 日志注解
*/
//Type代表可以放在类上面,Method代表可以放在方法上
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {
String module() default "";
String operation() default "";
}
对应设置方法输出日志
@PostMapping("view/{id}")
@LogAnnotation(module="文章",operation="获取文章列表")
public Result findArticleById(@PathVariable("id") Long articleId) {
ArticleVo articleVo = articleService.findArticleById(articleId);
return Result.success(articleVo);
}
设置切点切面,不然上述的注解都不生效,扫描指定包,使之生效,这块目前不太会,后面学源码补全。
package com.mzlu.blog.common.aop;
import com.alibaba.fastjson.JSON;
import com.mzlu.blog.utils.HttpContextUtils;
import com.mzlu.blog.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
/**
* AOP的应用
*/
@Component
@Aspect//切面。定义了切面和切顶的关系(这块并不是很懂,得回头看)
@Slf4j
public class LogAspect {
@Pointcut("@annotation(com.mzlu.blog.common.aop.LogAnnotation)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//执行方法
Object result = point.proceed();
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//保存日志
recordLog(point, time);
return result;
}
private void recordLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
log.info("=====================log start================================");
log.info("module:{}",logAnnotation.module());
log.info("operation:{}",logAnnotation.operation());
//请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
log.info("request method:{}",className + "." + methodName + "()");
//请求的参数,如果无参,会报错,无参为null,无法获取args[0]
Object[] args = joinPoint.getArgs();
String params = JSON.toJSONString(args[0]);
log.info("params:{}",params);
//获取request 设置IP地址
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
log.info("ip:{}", IpUtils.getIpAddr(request));
log.info("excute time : {} ms",time);
log.info("=====================log end================================");
}
}
IPutils工具类
package com.mzlu.blog.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
/**
* 获取Ip
*
*/
@Slf4j
public class IpUtils {
/**
* 获取IP地址
* <p>
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = null, unknown = "unknown", seperator = ",";
int maxLength = 15;
try {
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
log.error("IpUtils ERROR ", e);
}
// 使用代理,则获取第一个IP地址
if (StringUtils.isEmpty(ip) && ip.length() > maxLength) {
int idx = ip.indexOf(seperator);
if (idx > 0) {
ip = ip.substring(0, idx);
}
}
return ip;
}
/**
* 获取ip地址
*
* @return
*/
public static String getIpAddr() {
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
return getIpAddr(request);
}
}
HttpContextUtils工具类
package com.mzlu.blog.utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* HttpServletRequest
*
*/
public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}
6.统一缓存优化
将数据保存在redis中,设置过期时间,这样访问的速度会更快
|