spring boot + mybatis + redis 配置

1.application.yml

#配置访问的URL
server:
servlet-path: /web
port: spring:
datasource:
druid:
# 数据库访问配置, 使用druid数据源
db-type: com.alibaba.druid.pool.DruidDataSource
#driver-class-name: oracle.jdbc.driver.OracleDriver
#url: jdbc:oracle:thin:@localhost::ORCL
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/spring?useSSL=false
username: root
password:
# 连接池配置
initial-size:
min-idle:
max-active:
# 连接等待超时时间
max-wait:
# 配置检测可以关闭的空闲连接间隔时间
time-between-eviction-runs-millis:
# 配置连接在池中的最小生存时间
min-evictable-idle-time-millis:
validation-query: select '' from dual
test-while-idle: true
test-on-borrow: false
test-on-return: false
# 打开PSCache,并且指定每个连接上PSCache的大小
pool-prepared-statements: true
max-open-prepared-statements:
max-pool-prepared-statement-per-connection-size:
# 配置监控统计拦截的filters, 去掉后监控界面sql无法统计, 'wall'用于防火墙
filters: stat,wall
    #reids 必须使用代理才可以使用,此处配置必须,否则无法使用
# Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔
aop-patterns: com.springboot.service.* # WebStatFilter配置
web-stat-filter:
enabled: true
# 添加过滤规则
url-pattern: /*
# 忽略过滤的格式
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*' # StatViewServlet配置
stat-view-servlet:
enabled: true
# 访问路径为/druid时,跳转到StatViewServlet
url-pattern: /druid/*
# 是否能够重置数据
reset-enable: false
# 需要账号密码才能访问控制台
login-username: druid
login-password: druid123
# IP白名单
# allow: 127.0.0.1
# IP黑名单(共同存在时,deny优先于allow)
# deny: 192.168.1.218 # 配置StatFilter
filter:
stat:
log-slow-sql: true redis:
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: 127.0.0.1
# Redis服务器连接端口
port: 6379
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
# 连接池中的最大空闲连接
max-idle: 8
# 连接池中的最小空闲连接
min-idle: 0
# 连接超时时间(毫秒)
timeout: 5000 #配置显示执行sql的语句
logging:
level:
com:
springboot:
mapper: debug

2. RedisConfig 配置

package com.springboot.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper; @Configuration
public class RedisConfig extends CachingConfigurerSupport { // 自定义缓存key生成策略
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
StringBuffer sb = new StringBuffer();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
} // 缓存管理器
@Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
// 设置缓存过期时间
cacheManager.setDefaultExpiration();
return cacheManager;
} @Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
setSerializer(template);// 设置序列化工具
template.afterPropertiesSet();
return template;
} private void setSerializer(StringRedisTemplate template) {
@SuppressWarnings({ "rawtypes", "unchecked" })
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
}
}

spring boot + Log

1.LogAspect 配置

package com.springboot.aspect;

import java.lang.reflect.Method;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
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.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import com.springboot.annotation.Log;
import com.springboot.dao.SysLogDao;
import com.springboot.domain.SysLog;
import com.springboot.util.HttpContextUtils;
import com.springboot.util.IPUtils; @Aspect
@Component
public class LogAspect { @Autowired
private SysLogDao sysLogDao; @Pointcut("@annotation(com.springboot.annotation.Log)")
public void pointcut() {
} @Around("pointcut()")
public void around(ProceedingJoinPoint point) {
long beginTime = System.currentTimeMillis();
try {
// 执行方法
point.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
// 执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
// 保存日志
saveLog(point, time);
} private void saveLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SysLog sysLog = new SysLog();
Log logAnnotation = method.getAnnotation(Log.class);
if (logAnnotation != null) {
// 注解上的描述
sysLog.setOperation(logAnnotation.value());
}
// 请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setMethod(className + "." + methodName + "()");
// 请求的方法参数值
Object[] args = joinPoint.getArgs();
// 请求的方法参数名称
LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
String[] paramNames = u.getParameterNames(method);
if (args != null && paramNames != null) {
String params = "";
for (int i = ; i < args.length; i++) {
params += " " + paramNames[i] + ": " + args[i];
}
sysLog.setParams(params);
}
// 获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
// 设置IP地址
sysLog.setIp(IPUtils.getIpAddr(request));
// 模拟一个用户名
sysLog.setUsername("mrbird");
sysLog.setTime((int) time);
Date date = new Date();
sysLog.setCreateTime(date);
// 保存系统日志
sysLogDao.saveSysLog(sysLog);
}
}

2.日志工具类 IPUtils 获取 IP

package com.springboot.util;

import javax.servlet.http.HttpServletRequest;

public class IPUtils {

    /**
* 获取IP地址
*
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
} }

3.工具类 HttpContextUtils

package com.springboot.util;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}

spring boot 中使用 Redis 与 Log的更多相关文章

  1. spring boot 中使用redis session

    spring boot 默认的httpsession是存在内存中.这种默认方式有几个缺点:1.当分布式部署时,存在session不一致的问题:2.当服务重启时session就会丢失,这时候用户就需要重 ...

  2. Spring Boot中使用Redis小结

    Spring Boot中除了对常用的关系型数据库提供了优秀的自动化支持之外,对于很多NoSQL数据库一样提供了自动化配置的支持,包括:Redis, MongoDB, 等. Redis简单介绍 Redi ...

  3. Spring Boot中使用redis的发布/订阅模式

    原文:https://www.cnblogs.com/meetzy/p/7986956.html redis不仅是一个非常强大的非关系型数据库,它同时还拥有消息中间件的pub/sub功能,在sprin ...

  4. Spring Boot 中集成 Redis 作为数据缓存

    只添加注解:@Cacheable,不配置key时,redis 中默认存的 key 是:users::SimpleKey [](1.redis-cli 中,通过命令:keys * 查看:2.key:缓存 ...

  5. Spring Boot中使用Redis数据库

    引入依赖 Spring Boot提供的数据访问框架Spring Data Redis基于Jedis.可以通过引入spring-boot-starter-redis来配置依赖关系. <depend ...

  6. 学习Spring Boot:(十七)Spring Boot 中使用 Redis

    前言 Redis 1 是一个由Salvatore Sanfilippo写的key-value存储系统. edis是一个开源的使用ANSI C语言编写.遵守BSD协议.支持网络.可基于内存亦可持久化的日 ...

  7. Spring Boot中使用Redis

    一.定义工程 创建一个spring boot模块 二.修改pom文件 在pom文件中添加Spring Boot与Redis整合依赖 <dependencies> <!--spring ...

  8. spring boot中集成Redis

    1 pom.xml文件中添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <arti ...

  9. 【redis】spring boot中 使用redis hash 操作 --- 之 使用redis实现库存的并发有序操作

    示例: @Autowired StringRedisTemplate redisTemplate; @Override public void dealRedis(Dealer dealer) { d ...

随机推荐

  1. 快速了解CSS3当中的HSLA 颜色值怎么算

    CSS3文档中提到:(HSLA) H是色度,取值在0度~360度之间,0度是红色,120度是绿色,240度是蓝色.360度也是红色. S是饱和度,是色彩的纯度,是一个百分比的值,取值在0%~100%, ...

  2. J2SE 5.0-memory management whitepaper--delete

    1.垃圾回收器期职责 开辟空间 任何引用可达的对象都在内存内 回收不再使用的内存 3.垃圾回收器概念 3.1.垃圾回收器期望的性能 垃圾回收器必须安全,存活的对象不应该被释放,应该释放的对象存活的时间 ...

  3. IIS w3wp对应的应用程序

    IIS7以前我們用IISApp查看IIS哪些服務已啟動,但在IIS7已經不適用了,新語法是appcmd.exe list wp.你可以在%windir%\system32\inetsrv\底下找到ap ...

  4. 38.spiderkeeper的配置

    配置spiderkeeper管理scrapy爬虫 1.安装所需文件包pip install spiderkeeper pip install scrapyd pip install scrapy_cl ...

  5. dbcp 连接池参数说明

    参考: http://commons.apache.org/proper/commons-dbcp/configuration.html https://www.cnblogs.com/happySm ...

  6. Android自定义View学习(二)

    绘制顺序 参考:HenCoder Android 开发进阶:自定义 View 1-5 绘制顺序 绘制过程 包括 背景 主体(onDraw()) 子 View(dispatchDraw()) 滑动边缘渐 ...

  7. vbox 按照增强工具 centos7

    命令:mount -t auto /dev/cdrom /mnt/cdrom 这命令就是把CentOS CDROM挂载在/mnt/cdrom目录中,这样我们就可以访问光盘里面的内容了.执行“mount ...

  8. 关于vector变量的size,是一个无符号数引发的bug。LeetCode 3 sum

    class Solution { public: vector<vector<int>> threeSum(vector<int>& a) { vector ...

  9. Servlet基本_オブジェクトのスコープ

    1.スコープ種類Servletには以下のスコープがあります.Request.Session.Applicationの順にスコープは広くなっていきます.・Applicationスコープ:アプリケーション ...

  10. Linux:TCP状态/半关闭/2MSL/端口复用

    TCP状态 CLOSED:表示初始状态. LISTEN:该状态表示服务器端的某个SOCKET处于监听状态,可以接受连接. SYN_SENT:这个状态与SYN_RCVD遥相呼应,当客户端SOCKET执行 ...