springboot整合MongoDB

简介
MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。

MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

运行环境
开发工具:intellij idea
JDK版本:1.8
项目管理工具:Maven 4.0.0

整合:
pom.xml配置依赖
springboot整合MongoDB
在application.yml中添加配置
springboot整合MongoDB
technology是数据库的名字
需要在MongoDB中添加数据库名字
我用的是Navicat 远程连接MongoDB,添加数据库名称
springboot整合MongoDB
现在需要些相关的代码
我这边些了一个日志模块拿来
实体类:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;

import java.io.Serializable;
import java.util.Map;

@Data
public class DataCenterLog implements Serializable {

@Id
private String id;//id

private int user_id;//用户id

private String request_url;//请求地址

private String params;//传入参数

private String request_method;//请求方法

private String create_date;//新建时间

private String operation;//操作

private String content;//内容

private String ip_address;//ip

private String name;//用户名

private String role_name;//角色

private String returned_content;//返回值

private String exception_name;//异常名

private String exception_msg;//异常内容

/**
 * 设置请求参数
 * @param paramMap
 */
public void setMapToParams(Map<String, String[]> paramMap) {
    if (paramMap == null){
        return;
    }
    StringBuilder params = new StringBuilder();
    for (Map.Entry<String, String[]> param : ((Map<String, String[]>)paramMap).entrySet()){
        params.append(("".equals(params.toString()) ? "" : "&") + param.getKey() + "=");
        String paramValue = (param.getValue() != null && param.getValue().length > 0 ? param.getValue()[0] : "");

// params.append(StringUtils.abbr(StringUtils.endsWithIgnoreCase(param.getKey(), “password”) ? “” : paramValue, 100));
}
this.params = params.toString();
}

}

接口:

public interface SysLogService {

boolean add(DataCenterLog syslog);

}

实现类:需要添加 private MongoTemplate mongoTemplate;

import io.*.boot.rpc.common.annotation.RpcProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

@Service
@RpcProvider
public class SysLogServiceImpl implements SysLogService {

@Autowired
private MongoTemplate mongoTemplate;

public boolean add(DataCenterLog syslog) {
    mongoTemplate.insert(syslog);
    return true;
}

}

调用接口:

import io.*.boot.rpc.common.annotation.RpcConsumer;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
public class WebLogAspect {

private final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

@RpcConsumer
SysLogService sysLogService;

@Pointcut("execution(* com.yankuang.*..*Controller.*(..))")
public void webLog() {
}

@Pointcut("execution( * com.yankuang.*..*Controller.*(..)) && !execution(* com.yankuang.*..*.add*(..)) && !execution(* com.yankuang.*..*.update*(..)) " +
        "&& !execution(* com.yankuang.*..*.delete*(..)) && !execution(* com.yankuang.*..*.find*(..))")
public void sysLog() {
}

/**
 * 添加业务逻辑方法切入点
 */
@Pointcut("execution(* com.yankuang.*..*.add*(..)) ")
public void insertCell() {
}

/**
 * 修改业务逻辑方法切入点
 */
@Pointcut("execution(* com.yankuang.*..*.update*(..)) ")
public void updateCell() {
}

/**
 * 删除业务逻辑方法切入点
 */
@Pointcut("execution(* com.yankuang.*..*.delete*(..)) ")
public void deleteCell() {
}

/**
 * 查询业务逻辑方法切入点
 */
@Pointcut("execution(* com.yankuang.*..*.find*(..)) ")
public void findCell() {
}

/**
 * 拦截异常处理
 */
@Pointcut("execution(* com.yankuang.*..restful.*Controller(..))") //切点
public void webExceptionLog() {
}


@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    // 记录下请求内容
    logger.info("访问地址 : " + request.getRequestURL().toString());// 访问地址
    logger.info("请求方式 : " + request.getMethod());// 请求方式
    logger.info("访问IP : " + InetAddress.getLocalHost().toString().substring(InetAddress.getLocalHost().toString().lastIndexOf("/") + 1));
    logger.info("执行了" + joinPoint.getTarget().getClass().getName() + "类的" + joinPoint.getSignature().getName() + "方法");// 获取哪个类哪个方法
    logger.info("传入参数 : " + Arrays.toString(joinPoint.getArgs()));//获取传入目标方法的参数对象
    logger.info("请求token : " + request.getHeader("token"));// 请求token
}

/**
 * 除增删改查(add,delete,update,find)之外的操作日志(后置通知)
 *
 * @param joinPoint
 * @param object
 */
@AfterReturning(returning = "object", pointcut = "sysLog()")
public void sysLog(JoinPoint joinPoint, Object object) throws Throwable {
    // 判断参数
    if (joinPoint.getArgs() == null) {// 没有参数
        return;
    }
    DataCenterLog syslog = new DataCenterLog();
    syslog.setContent(opContent(joinPoint));
    syslog.setCreate_date(DateUtils());
    syslog.setIp_address(InetAddress.getLocalHost().toString().substring(InetAddress.getLocalHost().toString().lastIndexOf("/") + 1));

    syslog.setReturned_content("返回内容为:" + object);
    sysLogService.add(syslog);
}

/**
 * 添加操作日志(后置通知)
 *
 * @param joinPoint
 * @param object
 */
@AfterReturning(returning = "object", pointcut = "insertCell()")
public void insertLog(JoinPoint joinPoint, Object object) throws Throwable {
    // 判断参数
    if (joinPoint.getArgs() == null) {// 没有参数
        return;
    }
    DataCenterLog syslog = new DataCenterLog();
    syslog.setContent(opContent(joinPoint));
    syslog.setCreate_date(DateUtils());
    syslog.setOperation("添加");
    syslog.setIp_address(InetAddress.getLocalHost().toString().substring(InetAddress.getLocalHost().toString().lastIndexOf("/") + 1));
    //JSONObject json = JSONObject.fromObject(object);//将java对象转换为json对象
    syslog.setReturned_content("返回内容为:" + object);
    sysLogService.add(syslog);
}

/**
 * 管理员删除操作日志(后置通知)
 *
 * @param joinPoint
 * @param object
 * @throws Throwable
 */
@AfterReturning(value = "deleteCell()", returning = "object")
public void deleteLog(JoinPoint joinPoint, Object object) throws Throwable {
    // 判断参数
    if (joinPoint.getArgs() == null) {// 没有参数
        return;
    }
    // 创建日志对象
    DataCenterLog syslog = new DataCenterLog();
    syslog.setContent(opContent(joinPoint));
    syslog.setCreate_date(DateUtils());
    syslog.setOperation("删除");
    syslog.setIp_address(InetAddress.getLocalHost().toString().substring(InetAddress.getLocalHost().toString().lastIndexOf("/") + 1));

    syslog.setReturned_content("返回内容为:" + object);
    sysLogService.add(syslog);
}

/**
 * 管理员修改操作日志(后置通知)
 *
 * @param joinPoint
 * @param object
 * @throws Throwable
 */
@AfterReturning(value = "updateCell()", returning = "object")
public void updateLog(JoinPoint joinPoint, Object object) throws Throwable {
    // 判断参数
    if (joinPoint.getArgs() == null) {// 没有参数
        return;
    }
    // 创建日志对象
    DataCenterLog syslog = new DataCenterLog();
    syslog.setContent(opContent(joinPoint));
    syslog.setCreate_date(DateUtils());
    syslog.setOperation("修改");
    syslog.setIp_address(InetAddress.getLocalHost().toString().substring(InetAddress.getLocalHost().toString().lastIndexOf("/") + 1));
    //JSONObject json = JSONObject.fromObject(object);//将java对象转换为json对象
    syslog.setReturned_content("返回内容为:" + object);
    sysLogService.add(syslog);
}


/**
 * 管理员查找操作日志(后置通知)
 *
 * @param joinPoint
 * @param object
 * @throws Throwable
 */
@AfterReturning(value = "findCell()", returning = "object")
public void findLog(JoinPoint joinPoint, Object object) throws Throwable {
    // 判断参数
    if (joinPoint.getArgs() == null) {// 没有参数
        return;
    }
    // 创建日志对象
    DataCenterLog syslog = new DataCenterLog();
    syslog.setContent(opContent(joinPoint));
    syslog.setCreate_date(DateUtils());
    syslog.setOperation("查询");
    syslog.setIp_address(InetAddress.getLocalHost().toString().substring(InetAddress.getLocalHost().toString().lastIndexOf("/") + 1));
    //JSONObject json = JSONObject.fromObject(object);//将java对象转换为json对象
    syslog.setReturned_content("返回内容为:" + object);
    sysLogService.add(syslog);
}

/**
 * 异常通知 用于拦截异常日志
 *
 * @param joinPoint
 * @param e
 */
@AfterThrowing(pointcut = "webExceptionLog()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    HttpSession session = request.getSession();
    //获取请求ip
    String ip = request.getRemoteAddr();
    //获取用户请求方法的参数并序列化为JSON格式字符串
    try {

        // 创建日志对象
        DataCenterLog syslog = new DataCenterLog();
        syslog.setContent(opContent(joinPoint));
        syslog.setCreate_date(DateUtils());
        syslog.setIp_address(InetAddress.getLocalHost().toString().substring(InetAddress.getLocalHost().toString().lastIndexOf("/") + 1));
        syslog.setException_name(e.getClass().getName());
        syslog.setException_msg(e.getMessage());
        //保存数据库
        sysLogService.add(syslog);
    } catch (Exception ex) {
        //记录本地异常日志
        e.printStackTrace();
    }
}

/**
 * 获取执行的操作的信息
 *
 * @param joinPoint
 * @return
 */
public String opContent(JoinPoint joinPoint) {
    //获取类名
    String className = joinPoint.getTarget().getClass().getName();
    //获取方法名
    String methodName = joinPoint.getSignature().getName();
    String str = "执行了" + className + "类的" + methodName + "方法";
    return str;
}

public String DateUtils() {
    Date d = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateNowStr = sdf.format(d);
    return dateNowStr;
}

}

postman调用接口进行测试
写一个测试类:
springboot整合MongoDB
执行后控制台会出现log日志
springboot整合MongoDB
随之,查看Navicat 相应的数据库中会多个一个表,就是刚刚创建的实体类的名字
springboot整合MongoDB
将数据已经添加到了表里:
springboot整合MongoDB
结束!

上一篇:java 自定义注解+AOP实现日志记录


下一篇:【AOP】在Aspect中无法获取实现类方法的注解