前面二手房管理里面用到了大量的数据字典数据,这些数据基本不会更新,访问频率又很高,那边实时访问数据库就不是很合适了,怎么办?缓存,redis 是一个高性能的key-value内存数据库,性能极高,官方数据:redis能读的速度是110000次/s,写的速度是81000次/s,因此我们用redis做字典数据缓存是最好的选择。
jedis是redis官方推荐的Java连接开发工具。要在java开发中使用好redis中间件,必须对jedis熟悉才能写成漂亮的代码。
1、shf-parent模块pom.xml添加依赖管理
<jedis.version>2.9.0jedis.version>
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
<version>${jedis.version}version>
dependency>
2、common-util模块引入依赖
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
dependency>
参考:https://www.runoob.com/redis/redis-install.html
操作模块:service-house
spring/spring-redis.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="100">property>
<property name="maxIdle" value="50">property>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
bean>
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg name="poolConfig" ref="jedisPoolConfig" />
<constructor-arg name="host" value="192.168.6.100" />
<constructor-arg name="port" value="6379" type="int" />
<constructor-arg name="timeout" value="5000" type="int" />
bean>
beans>
修改DictServiceImpl类
package com.atguigu.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.atguigu.dao.DictDao;
import com.atguigu.entity.Dict;
import com.atguigu.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service(interfaceClass = DictService.class)
public class DictServiceImpl implements DictService {
@Autowired
private DictDao dictDao;
@Autowired
private JedisPool jedisPool;
@Override
public List<Map<String,Object>> findZnodes(Long id) {
// 返回数据[{ id:2, isParent:true, name:"随意勾选 2"}]
//根据id获取子节点数据
//判断该节点是否是父节点
//获取子节点数据列表
List<Dict> dictList = dictDao.findListByParentId(id);
//构建ztree数据
List<Map<String,Object>> zNodes = new ArrayList<>();
for(Dict dict : dictList) {
Integer count = dictDao.countIsParent(dict.getId());
Map<String,Object> map = new HashMap<>();
map.put("id", dict.getId());
map.put("isParent", count > 0 ? true : false);
map.put("name", dict.getName());
zNodes.add(map);
};
return zNodes;
}
@Override
public List<Dict> findDictListByParentDictCode(String parentDictCode) {
Jedis jedis = null;
try {
//从redis中查找是否存有当前父节点的子节点列表
jedis = jedisPool.getResource();
String value = jedis.get("zfw:dict:parentDictCode:" + parentDictCode);
if (!StringUtils.isEmpty(value)) {
//redis中有数据,则将该数据转成List并返回
return JSON.parseArray(value, Dict.class);
}
//redis中没有数据
List<Dict> dictList = dictMapper.findDictListByParentDictCode(parentDictCode);
//将DictList转成JSON并存储到redis中
if (!CollectionUtils.isEmpty(dictList)) {
jedis.set("zfw:dict:parentDictCode:" + parentDictCode, JSON.toJSONString(dictList));
}
return dictList;
} finally {
if (jedis != null) {
jedis.close();
if (jedis.isConnected()) {
jedis.disconnect();
}
}
}
}
@Override
public List<Dict> findDictListByParentId(Long parentId) {
Jedis jedis = null;
try {
//从redis中查找是否存有当前父节点的子节点列表
jedis = jedisPool.getResource();
String value = jedis.get("zfw:dict:parentId:" + parentId);
if (!StringUtils.isEmpty(value)) {
//redis中有数据,则将该数据转成List并返回
return JSON.parseArray(value, Dict.class);
}
//redis中没有数据,则从数据库查询
List<Dict> dictList = dictMapper.findListByParentId(parentId);
//将DictList转成JSON并存储到redis中
if (!CollectionUtils.isEmpty(dictList)) {
jedis.set("zfw:dict:parentId:" + parentId, JSON.toJSONString(dictList));
}
return dictList;
} finally {
//关闭jedis
if (jedis != null) {
jedis.close();
}
if (jedis.isConnected()) {
jedis.disconnect();
}
}
}
}
系统中要记录操作日志,操作日志会记录每一个登录用户的所有操作,对于运营系统很重要,那么是怎么实现的呢?AOP,即面向切面编程,我们就用spring AOP对controller进行监控,实时记录日志
在spring-mvc.xml添加配置
<aop:aspectj-autoproxy/>
更改包扫描为:com.atguigu
<context:component-scan base-package="com.atguigu" />
添加ControllerAspect类
package com.atguigu.aspect;
import com.atguigu.util.IpUtil;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* 包名:com.atguigu.aspect
*
* @author Leevi
* 日期2022-05-31 10:18
* 切入点: 用来描述那些需要去增强/改变的方法
* 通知: 封装了增强/改变的代码的方法
* 切面: 存放通知的类
*/
@Component
@Aspect
public class ControllerAspect {
/**
* SLF4J的日志记录器对象
*/
private Logger logger = LoggerFactory.getLogger(ControllerAspect.class);
@Pointcut("execution(* com.atguigu.controller.*.*(..))")
public void controllerAction(){
}
/**
* 记录操作日志:
* 用户名 | url | 请求方式 | ip地址 | 调用的方法 | 调用方法时候的参数 | 执行时间
* @param proceedingJoinPoint
* @return
*/
@Around("controllerAction()")
public Object recordLogs(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
//创建StringBuilder用来拼接日志内容
StringBuilder stringBuilder = new StringBuilder("");
//1. 获取用户名
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication.getPrincipal() instanceof User)) {
//说明没登录,不记录操作
return proceedingJoinPoint.proceed();
}
//如果登录了
User user = (User) authentication.getPrincipal();
//获取到用户名
String username = user.getUsername();
stringBuilder.append(username);
//2. 获取请求相关的数据
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
//获取请求对象
HttpServletRequest request = sra.getRequest();
//2.1 获取url
String url = request.getRequestURL().toString();
stringBuilder.append("|"+url);
//2.2 获取请求方式
String method = request.getMethod();
stringBuilder.append("|"+method);
//2.3 获取IP地址
String ipAddress = IpUtil.getIpAddress(request);
stringBuilder.append("|"+ipAddress);
//3. 获取切入点相关的信息
//3.1 获取调用的方法: 类的全限定名.方法名
Signature signature = proceedingJoinPoint.getSignature();
String classMethod = signature.getDeclaringTypeName() + "." + signature.getName();
stringBuilder.append("|"+classMethod);
//3.2 获取方法的参数
Object[] args = proceedingJoinPoint.getArgs();
if (args != null && args.length > 0) {
stringBuilder.append("|");
for (int i = 0; i < args.length; i++) {
if (i < args.length - 1) {
//遍历出每一个参数
stringBuilder.append(args[i] + ",");
}else {
stringBuilder.append(args[i]);
}
}
}
long startTime = 0;
try {
//4. 获取执行时长
//4.1 获取切入点执行之前的时间
startTime = System.currentTimeMillis();
//4.2 执行切入点
return proceedingJoinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
throw throwable;
} finally {
//4.3 记录执行切入点之后的时间
long endTime = System.currentTimeMillis();
//4.4 计算出方法的执行时长
long executeTime = endTime - startTime;
stringBuilder.append("|"+executeTime);
logger.info("request logs:"+stringBuilder);
}
}
}