springboot:整合其它项目
创始人
2024-04-03 06:55:28

目录

一、集成Druid

application.yml

二、集成redis之非注解式开发

pom.xml

application.yml

RedisConfig 

ClazzBizImpl.java

三、集成redis之注解缓存开发

RedisConfig 

 RedisConfig 


一、集成Druid

在昨天的基础上

参考网址

https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

添加pom依赖

     com.alibabadruid-spring-boot-starter1.1.10

配置

application.yml

mybatis:mapper-locations: classpath:mappers/*xmltype-aliases-package: com.cdl.springboot04.model
server:port: 8080servlet:context-path: /springboot04
spring:application:name: springboot04datasource:driver-class-name: com.mysql.jdbc.Drivername: defaultDataSourcepassword: 123456url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=UTF-8&useSSL=falseusername: roottype: com.alibaba.druid.pool.DruidDataSourcedruid:#2.连接池配置#初始化连接池的连接数量 大小,最小,最大initial-size: 5min-idle: 5max-active: 20#配置获取连接等待超时的时间max-wait: 60000#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒time-between-eviction-runs-millis: 60000# 配置一个连接在池中最小生存的时间,单位是毫秒min-evictable-idle-time-millis: 30000validation-query: SELECT 1 FROM DUALtest-while-idle: truetest-on-borrow: truetest-on-return: false# 是否缓存preparedStatement,也就是PSCache  官方建议MySQL下建议关闭   个人建议如果想用SQL防火墙 建议打开pool-prepared-statements: truemax-pool-prepared-statement-per-connection-size: 20# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙filter:stat:merge-sql: trueslow-sql-millis: 5000#3.基础监控配置web-stat-filter:enabled: trueurl-pattern: /*#设置不统计哪些URLexclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"session-stat-enable: truesession-stat-max-count: 100stat-view-servlet:enabled: trueurl-pattern: /druid/*reset-enable: true#设置监控页面的登录名和密码login-username: adminlogin-password: adminallow: 127.0.0.1#deny: 192.168.1.100freemarker:cache: falsecharset: utf-8expose-request-attributes: trueexpose-session-attributes: truesuffix: .ftltemplate-loader-path: classpath:/templates/
#    resources:
#       static-locations: classpath:/static/# 应用服务 WEB 访问端口mvc:static-path-pattern: classpath:/static/
pagehelper:reasonable: truesupportMethodsArguments: truepage-size-zero: truehelper-dialect: mysqllogging:level:com.cdl.springboot04: debug

运行启动类

打开我们的班级列表

 通过手动输入druid的登录界面

 登录之后

 当我们对班级列表进行操作时,例如增加

 此时SQL监控,URL监控

若增加一个重复的id 则URL监控就显示error

 

二、集成redis之非注解式开发

添加需要的pom依赖


org.springframework.bootspring-boot-starter-data-redis

pom.xml


4.0.0com.cdlspringboot040.0.1-SNAPSHOTspringboot04Demo project for Spring Boot1.8UTF-8UTF-82.3.7.RELEASEorg.springframework.bootspring-boot-starter-freemarkerorg.springframework.bootspring-boot-starter-jdbcorg.springframework.bootspring-boot-starter-weborg.mybatis.spring.bootmybatis-spring-boot-starter2.1.4mysqlmysql-connector-java5.1.44org.springframeworkspring-aspects5.0.2.RELEASEcom.github.pagehelperpagehelper-spring-boot-starter1.2.3com.alibabadruid-spring-boot-starter1.1.10org.springframework.bootspring-boot-starter-data-redisorg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-testtestorg.junit.vintagejunit-vintage-engineorg.springframework.bootspring-boot-dependencies${spring-boot.version}pomimportorg.apache.maven.pluginsmaven-compiler-plugin3.8.11.81.8UTF-8org.springframework.bootspring-boot-maven-plugin2.3.7.RELEASEcom.cdl.springboot04.Springboot04Applicationrepackagerepackage

配置

application.yml

mybatis:mapper-locations: classpath:mappers/*xmltype-aliases-package: com.cdl.springboot04.model
server:port: 8080servlet:context-path: /springboot04
spring:application:name: springboot04datasource:driver-class-name: com.mysql.jdbc.Drivername: defaultDataSourcepassword: 123456url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=UTF-8&useSSL=falseusername: roottype: com.alibaba.druid.pool.DruidDataSourcedruid:#2.连接池配置#初始化连接池的连接数量 大小,最小,最大initial-size: 5min-idle: 5max-active: 20#配置获取连接等待超时的时间max-wait: 60000#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒time-between-eviction-runs-millis: 60000# 配置一个连接在池中最小生存的时间,单位是毫秒min-evictable-idle-time-millis: 30000validation-query: SELECT 1 FROM DUALtest-while-idle: truetest-on-borrow: truetest-on-return: false# 是否缓存preparedStatement,也就是PSCache  官方建议MySQL下建议关闭   个人建议如果想用SQL防火墙 建议打开pool-prepared-statements: truemax-pool-prepared-statement-per-connection-size: 20# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙filter:stat:merge-sql: trueslow-sql-millis: 5000#3.基础监控配置web-stat-filter:enabled: trueurl-pattern: /*#设置不统计哪些URLexclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"session-stat-enable: truesession-stat-max-count: 100stat-view-servlet:enabled: trueurl-pattern: /druid/*reset-enable: true#设置监控页面的登录名和密码login-username: adminlogin-password: adminallow: 127.0.0.1#deny: 192.168.1.100freemarker:cache: falsecharset: utf-8expose-request-attributes: trueexpose-session-attributes: truesuffix: .ftltemplate-loader-path: classpath:/templates/
#    resources:
#       static-locations: classpath:/static/# 应用服务 WEB 访问端口mvc:static-path-pattern: classpath:/static/redis:host: 192.168.26.128port: 6379database: 0password: 123456
pagehelper:reasonable: truesupportMethodsArguments: truepage-size-zero: truehelper-dialect: mysqllogging:level:com.cdl.springboot04: debug

新建一个包 config 配置类

RedisConfig 

package com.cdl.springboot04.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;/*** @author CDL* @site www.cdl.com** @Configuration:凡是被@Configuration注解所标记,就代表当前这个类为配置类* 而配置类等价于ssm阶段中spring-*.xml这一类的配置文件** spring-*.xml中:* @Bean:代表某个类交给spring进行管理****/
@Configuration
public class RedisConfig {@Beanpublic RedisTemplate getRedisTemplate(RedisConnectionFactory connectionFactory){RedisTemplate redisTemplate = new RedisTemplate<>();//配置序列化器  针对于key 针对于valueredisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
//        redisTemplate.afterPropertiesSet();根据redis的版本考虑要不要让其生效//ConnectionFactory是包含了redis的连接信息redisTemplate.setConnectionFactory(connectionFactory);return redisTemplate;}
}

在service层ClazzBizImpl.java使用

ClazzBizImpl.java

package com.cdl.springboot04.biz.impl;import com.cdl.springboot04.biz.ClazzBiz;
import com.cdl.springboot04.mapper.ClazzMapper;
import com.cdl.springboot04.model.Clazz;
import com.cdl.springboot04.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;import java.util.List;
import java.util.Map;/*** @author CDL* @site www.cdl.com* @company xxx公司* @create  2022-08-17 15:13*/
@Service
public class ClazzBizImpl implements ClazzBiz {@Autowiredprivate ClazzMapper clazzMapper;@Autowiredprivate RedisTemplate redisTemplate;@Overridepublic int deleteByPrimaryKey(Integer cid) {
//        System.out.println("不做任何操作...");return clazzMapper.deleteByPrimaryKey(cid);
//        return 0;}@Overridepublic int insert(Clazz record) {return clazzMapper.insert(record);}@Overridepublic int insertSelective(Clazz record) {return clazzMapper.insertSelective(record);}@Overridepublic Clazz selectByPrimaryKey(Integer cid) {return clazzMapper.selectByPrimaryKey(cid);}@Overridepublic int updateByPrimaryKeySelective(Clazz record) {return clazzMapper.updateByPrimaryKeySelective(record);}@Overridepublic int updateByPrimaryKey(Clazz record) {return clazzMapper.updateByPrimaryKey(record);}@Overridepublic List listPager(Clazz clazz, PageBean pageBean) {//将班级缓存到redis中List clzs = clazzMapper.listPager(clazz);// redisTemplate.opsForValue().set("clz:1",clzs.get(0));redisTemplate.opsForValue().set("clzs",clzs);// redisTemplate.opsForHash().entries();return clzs;}@Overridepublic List listMapPager(Clazz clazz, PageBean pageBean) {if(true)throw new RuntimeException("查询班级信息异常,异常存在于ClazzBizImpl.list。。。。");return clazzMapper.listMapPager(clazz);}
}

运行:

 此时:可见已经缓存进去了

三、集成redis之注解缓存开发

还要在配置类配置缓存管理器

RedisConfig 

package com.cdl.springboot04.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
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.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;/*** @author CDL* @site www.cdl.com** @Configuration:凡是被@Configuration注解所标记,就代表当前这个类为配置类* 而配置类等价于ssm阶段中spring-*.xml这一类的配置文件** spring-*.xml中:* @Bean:代表某个类交给spring进行管理****/
@Configuration
public class RedisConfig {private final int defaultExpireTime = 600;//默认的缓存槽private final int userCacheExpireTime = 60;//用来缓存用户的槽private final String userCacheName = "test";//用户槽的名称@Beanpublic RedisTemplate getRedisTemplate(RedisConnectionFactory connectionFactory){RedisTemplate redisTemplate = new RedisTemplate<>();//配置序列化器  针对于key 针对于valueredisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
//        redisTemplate.afterPropertiesSet();根据redis的版本考虑要不要让其生效//ConnectionFactory是包含了redis的连接信息redisTemplate.setConnectionFactory(connectionFactory);return redisTemplate;}@Bean//配置缓存管理器public RedisCacheManager redis(RedisConnectionFactory connectionFactory){RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();// 设置缓存管理器管理的缓存的默认过期时间defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(defaultExpireTime))// 设置 key为string序列化.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))// 设置value为json序列化.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))// 不缓存空值.disableCachingNullValues();Set cacheNames = new HashSet<>();cacheNames.add(userCacheName);// 对每个缓存空间应用不同的配置Map configMap = new HashMap<>();configMap.put(userCacheName, defaultCacheConfig.entryTtl(Duration.ofSeconds(userCacheExpireTime)));RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory).cacheDefaults(defaultCacheConfig).initialCacheNames(cacheNames).withInitialCacheConfigurations(configMap).build();return cacheManager;}
}

将非注解式缓存的Java代码注掉

 RedisConfig 

package com.cdl.springboot04.config;import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
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.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;/*** @author CDL* @site www.cdl.com** @Configuration:凡是被@Configuration注解所标记,就代表当前这个类为配置类* 而配置类等价于ssm阶段中spring-*.xml这一类的配置文件** spring-*.xml中:* @Bean:代表某个类交给spring进行管理***@EnableCaching 替代了下面的配置*  */
@EnableCaching//开启缓存
@Configuration
public class RedisConfig {private final int defaultExpireTime = 600;//默认的缓存槽private final int userCacheExpireTime = 60;//用来缓存用户的槽private final String userCacheName = "test";//用户槽的名称@Beanpublic RedisTemplate getRedisTemplate(RedisConnectionFactory connectionFactory){RedisTemplate redisTemplate = new RedisTemplate<>();//配置序列化器  针对于key 针对于valueredisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
//        redisTemplate.afterPropertiesSet();根据redis的版本考虑要不要让其生效//ConnectionFactory是包含了redis的连接信息redisTemplate.setConnectionFactory(connectionFactory);return redisTemplate;}@Bean//配置缓存管理器public RedisCacheManager redis(RedisConnectionFactory connectionFactory){RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();// 设置缓存管理器管理的缓存的默认过期时间defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(defaultExpireTime))// 设置 key为string序列化.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))// 设置value为json序列化.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))// 不缓存空值.disableCachingNullValues();Set cacheNames = new HashSet<>();cacheNames.add(userCacheName);// 对每个缓存空间应用不同的配置Map configMap = new HashMap<>();configMap.put(userCacheName, defaultCacheConfig.entryTtl(Duration.ofSeconds(userCacheExpireTime)));RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory).cacheDefaults(defaultCacheConfig).initialCacheNames(cacheNames).withInitialCacheConfigurations(configMap).build();return cacheManager;}
}

 测试查询单个能不能缓存进去

给查询单个的方法添加注解

 在ClazzController中添加一个查询单个的方法

  @ResponseBody@RequestMapping("/load")public Clazz load(Clazz clazz, HttpServletRequest request){return clazzBiz.selectByPrimaryKey(clazz.getCid());}

启动前先将redis中的数据清空

 访问数据

 缓存成功

 换个槽看下 时间

 查看单个

 缓存

 

 

相关内容

热门资讯

埃菲尔铁塔在哪 中国仿建埃菲尔... 2019年4月26日,广西南宁市,街头惊现一座巨型山寨版埃菲尔铁塔,高约20米,白色塔身,造型逼真,...
苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...
北京的名胜古迹 北京最著名的景... 北京从元代开始,逐渐走上帝国首都的道路,先是成为大辽朝五大首都之一的南京城,随着金灭辽,金代从海陵王...
长白山自助游攻略 吉林长白山游... 昨天介绍了西坡的景点详细请看链接:一个人的旅行,据说能看到长白山天池全凭运气,您的运气如何?今日介绍...
应用未安装解决办法 平板应用未... ---IT小技术,每天Get一个小技能!一、前言描述苹果IPad2居然不能安装怎么办?与此IPad不...
脚上的穴位图 脚面经络图对应的... 人体穴位作用图解大全更清晰直观的标注了各个人体穴位的作用,包括头部穴位图、胸部穴位图、背部穴位图、胳...
猫咪吃了塑料袋怎么办 猫咪误食... 你知道吗?塑料袋放久了会长猫哦!要说猫咪对塑料袋的喜爱程度完完全全可以媲美纸箱家里只要一有塑料袋的响...
demo什么意思 demo版本... 618快到了,各位的小金库大概也在准备开闸放水了吧。没有小金库的,也该向老婆撒娇卖萌服个软了,一切只...
世界上最漂亮的人 世界上最漂亮... 此前在某网上,选出了全球265万颜值姣好的女性。从这些数量庞大的女性群体中,人们投票选出了心目中最美...
埃菲尔铁塔在哪 中国仿建埃菲尔... 2019年4月26日,广西南宁市,街头惊现一座巨型山寨版埃菲尔铁塔,高约20米,白色塔身,造型逼真,...
苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...
北京的名胜古迹 北京最著名的景... 北京从元代开始,逐渐走上帝国首都的道路,先是成为大辽朝五大首都之一的南京城,随着金灭辽,金代从海陵王...
长白山自助游攻略 吉林长白山游... 昨天介绍了西坡的景点详细请看链接:一个人的旅行,据说能看到长白山天池全凭运气,您的运气如何?今日介绍...
世界上最漂亮的人 世界上最漂亮... 此前在某网上,选出了全球265万颜值姣好的女性。从这些数量庞大的女性群体中,人们投票选出了心目中最美...
应用未安装解决办法 平板应用未... ---IT小技术,每天Get一个小技能!一、前言描述苹果IPad2居然不能安装怎么办?与此IPad不...
脚上的穴位图 脚面经络图对应的... 人体穴位作用图解大全更清晰直观的标注了各个人体穴位的作用,包括头部穴位图、胸部穴位图、背部穴位图、胳...
demo什么意思 demo版本... 618快到了,各位的小金库大概也在准备开闸放水了吧。没有小金库的,也该向老婆撒娇卖萌服个软了,一切只...
猫咪吃了塑料袋怎么办 猫咪误食... 你知道吗?塑料袋放久了会长猫哦!要说猫咪对塑料袋的喜爱程度完完全全可以媲美纸箱家里只要一有塑料袋的响...