• springboot整合其它项目


    目录

    一、集成Druid

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

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


    一、集成Druid

    学习地址:

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

    添加配置,不要最新的,进过测试SQL监控失效

    pom依赖:(注意别放错了哦)

     
                com.alibaba
                druid-spring-boot-starter
                1.1.10
     

    添加Druid配置到yml文件:

    type:com.alibaba.druid.pool.DruidDataSource
    druid:
        #2.连接池配置
        #初始化连接池的连接数量 大小,最小,最大
        initial-size: 5
        min-idle: 5
        max-active: 20
        #配置获取连接等待超时的时间
        max-wait: 60000
        #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        time-between-eviction-runs-millis: 60000
        # 配置一个连接在池中最小生存的时间,单位是毫秒
        min-evictable-idle-time-millis: 30000
        validation-query: SELECT 1 FROM DUAL
        test-while-idle: true
        test-on-borrow: true
        test-on-return: false
        # 是否缓存preparedStatement,也就是PSCache  官方建议MySQL下建议关闭   个人建议如果想用SQL防火墙 建议打开
        pool-prepared-statements: true
        max-pool-prepared-statement-per-connection-size: 20
        # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
        filter:
            stat:
                merge-sql: true
                slow-sql-millis: 5000
        #3.基础监控配置
        web-stat-filter:
            enabled: true
            url-pattern: /*
            #设置不统计哪些URL
            exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
            session-stat-enable: true
            session-stat-max-count: 100
        stat-view-servlet:
            enabled: true
            url-pattern: /druid/*
            reset-enable: true
            #设置监控页面的登录名和密码
            login-username: admin
            login-password: admin
            allow: 127.0.0.1
            #deny: 192.168.1.100

    用户名和密码对应如下: 

     

     

    当运行了http://localhost:8080/spboot04/clz/list 时,下面URL监控就会显示:

     (SQL监控也能看到)

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

    pom.xml:

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

     yml配置:

    1. mybatis:
    2. mapper-locations: classpath:mappers/*xml
    3. type-aliases-package: com.ycx.spboot04.model
    4. server:
    5. port: 8080
    6. servlet:
    7. context-path: /spboot04
    8. spring:
    9. application:
    10. name: spboot04
    11. datasource:
    12. driver-class-name: com.mysql.jdbc.Driver
    13. name: defaultDataSource
    14. password: 1234
    15. url: jdbc:mysql://localhost:3306/yjy?useUnicode=true&characterEncoding=UTF-8
    16. username: root
    17. type: com.alibaba.druid.pool.DruidDataSource
    18. druid:
    19. #2.连接池配置
    20. #初始化连接池的连接数量 大小,最小,最大
    21. initial-size: 5
    22. min-idle: 5
    23. max-active: 20
    24. #配置获取连接等待超时的时间
    25. max-wait: 60000
    26. #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    27. time-between-eviction-runs-millis: 60000
    28. # 配置一个连接在池中最小生存的时间,单位是毫秒
    29. min-evictable-idle-time-millis: 30000
    30. validation-query: SELECT 1 FROM DUAL
    31. test-while-idle: true
    32. test-on-borrow: true
    33. test-on-return: false
    34. # 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开
    35. pool-prepared-statements: true
    36. max-pool-prepared-statement-per-connection-size: 20
    37. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    38. filter:
    39. stat:
    40. merge-sql: true
    41. slow-sql-millis: 5000
    42. #3.基础监控配置
    43. web-stat-filter:
    44. enabled: true
    45. url-pattern: /*
    46. #设置不统计哪些URL
    47. exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
    48. session-stat-enable: true
    49. session-stat-max-count: 100
    50. stat-view-servlet:
    51. enabled: true
    52. url-pattern: /druid/*
    53. reset-enable: true
    54. #设置监控页面的登录名和密码
    55. login-username: admin
    56. login-password: admin
    57. allow: 127.0.0.1
    58. #deny: 192.168.1.100
    59. freemarker:
    60. cache: false
    61. charset: utf-8
    62. expose-request-attributes: true
    63. expose-session-attributes: true
    64. suffix: .ftl
    65. template-loader-path: classpath:/templates/
    66. # resources:
    67. # static-locations: classpath:/static/# 应用服务 WEB 访问端口
    68. mvc:
    69. static-path-pattern: /static/**
    70. redis:
    71. host:192.168.122.128
    72. password:
    73. port: 6379
    74. database: 0
    75. pagehelper:
    76. reasonable: true
    77. supportMethodsArguments: true
    78. page-size-zero: true
    79. helper-dialect: mysql
    80. #logging:
    81. # level:
    82. # com.ycx.spboot04:debug

    RedisConfig :

    1. package com.ycx.spboot04.config;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.Configuration;
    4. import org.springframework.data.redis.connection.RedisConnectionFactory;
    5. import org.springframework.data.redis.core.RedisTemplate;
    6. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
    7. import org.springframework.data.redis.serializer.StringRedisSerializer;
    8. /**
    9. * @author 杨总
    10. * @create 2022-11-02 22:03
    11. *
    12. * @Configuration:凡是被@Configuration注解所标记,就代表当前这个类为配置类
    13. * 而配置类等价于ssm阶段中spring-*.xml这一类的配置文件
    14. *
    15. * spring-*.xml
    16. *
    17. * 将redistemplate进行配置,然后交给spring进行管理
    18. */
    19. @Configuration
    20. public class RedisConfig {
    21. @Bean
    22. public RedisTemplate<String,Object> getRedisTemplate(RedisConnectionFactory connectionFactory){
    23. RedisTemplate<String,Object> redisTemplate=new RedisTemplate<>();
    24. // 配置序列化器
    25. //针对于key
    26. redisTemplate.setKeySerializer(new StringRedisSerializer());
    27. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    28. //针对于value
    29. redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    30. redisTemplate.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
    31. // redisTemplate.afterPropertiesSet();//根据不同的redis版本
    32. // connectionFactory是包含了redis的连接信息
    33. redisTemplate.setConnectionFactory(connectionFactory);
    34. return redisTemplate;
    35. }
    36. }

     ClazzBizImpl :

    1. package com.ycx.spboot04.biz.impl;
    2. import com.ycx.spboot04.biz.ClazzBiz;
    3. import com.ycx.spboot04.mapper.ClazzMapper;
    4. import com.ycx.spboot04.model.Clazz;
    5. import com.ycx.spboot04.util.PageBean;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.data.redis.core.RedisTemplate;
    8. import org.springframework.stereotype.Service;
    9. import java.util.List;
    10. import java.util.Map;
    11. @Service
    12. public class ClazzBizImpl implements ClazzBiz {
    13. @Autowired
    14. private ClazzMapper clazzMapper;
    15. @Autowired
    16. private RedisTemplate<String,Object> redisTemplate;
    17. @Override
    18. public int deleteByPrimaryKey(Integer cid) {
    19. System.out.println("不做任何操作...");
    20. return clazzMapper.deleteByPrimaryKey(cid);
    21. // return 0;
    22. }
    23. @Override
    24. public int insert(Clazz record) {
    25. return clazzMapper.insert(record);
    26. }
    27. @Override
    28. public int insertSelective(Clazz record) {
    29. return clazzMapper.insertSelective(record);
    30. }
    31. @Override
    32. public Clazz selectByPrimaryKey(Integer cid) {
    33. return clazzMapper.selectByPrimaryKey(cid);
    34. }
    35. @Override
    36. public int updateByPrimaryKeySelective(Clazz record) {
    37. return clazzMapper.updateByPrimaryKeySelective(record);
    38. }
    39. @Override
    40. public int updateByPrimaryKey(Clazz record) {
    41. return clazzMapper.updateByPrimaryKey(record);
    42. }
    43. @Override
    44. public List<Clazz> listPager(Clazz clazz, PageBean pageBean) {
    45. List<Clazz> clazzes = clazzMapper.listPager(clazz);
    46. // 将班级信息缓存到redis中
    47. redisTemplate.opsForValue().set("clz_infos",clazzes);
    48. return clazzes;
    49. }
    50. @Override
    51. public List<Map> listMapPager(Clazz clazz, PageBean pageBean) {
    52. if(true)
    53. throw new RuntimeException("查询班级信息异常,异常存在于ClazzBizImpl.list。。。。");
    54. return clazzMapper.listMapPager(clazz);
    55. }
    56. }

     

     测试,记得打开虚拟机,再打开redis查看:

     

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

    注解式缓存

    RedisConfig :

    1. package com.ycx.spboot04.config;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.Configuration;
    4. import org.springframework.data.redis.cache.RedisCacheConfiguration;
    5. import org.springframework.data.redis.cache.RedisCacheManager;
    6. import org.springframework.data.redis.connection.RedisConnectionFactory;
    7. import org.springframework.data.redis.core.RedisTemplate;
    8. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
    9. import org.springframework.data.redis.serializer.RedisSerializationContext;
    10. import org.springframework.data.redis.serializer.StringRedisSerializer;
    11. import java.time.Duration;
    12. import java.util.HashMap;
    13. import java.util.HashSet;
    14. import java.util.Map;
    15. import java.util.Set;
    16. /**
    17. * @author 杨总
    18. * @create 2022-11-02 22:03
    19. *
    20. * @Configuration:凡是被@Configuration注解所标记,就代表当前这个类为配置类
    21. * 而配置类等价于ssm阶段中spring-*.xml这一类的配置文件
    22. *
    23. * spring-*.xml
    24. *
    25. * 将redistemplate进行配置,然后交给spring进行管理
    26. */
    27. @Configuration
    28. public class RedisConfig {
    29. private final int defaultExpireTime = 600;
    30. private final int userCacheExpireTime = 60;
    31. private final String userCacheName = "test";
    32. @Bean
    33. public RedisTemplate<String,Object> getRedisTemplate(RedisConnectionFactory connectionFactory){
    34. RedisTemplate<String,Object> redisTemplate=new RedisTemplate<>();
    35. // 配置序列化器
    36. //针对于key
    37. redisTemplate.setKeySerializer(new StringRedisSerializer());
    38. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    39. //针对于value
    40. redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    41. redisTemplate.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
    42. // redisTemplate.afterPropertiesSet();//根据不同的redis版本
    43. // connectionFactory是包含了redis的连接信息
    44. redisTemplate.setConnectionFactory(connectionFactory);
    45. return redisTemplate;
    46. }
    47. @Bean
    48. public RedisCacheManager redis(RedisConnectionFactory connectionFactory){
    49. RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
    50. // 设置缓存管理器管理的缓存的默认过期时间
    51. defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(defaultExpireTime))
    52. // 设置 key为string序列化
    53. .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
    54. // 设置value为json序列化
    55. .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
    56. // 不缓存空值
    57. .disableCachingNullValues();
    58. Set<String> cacheNames = new HashSet<>();
    59. cacheNames.add(userCacheName);
    60. // 对每个缓存空间应用不同的配置
    61. Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
    62. configMap.put(userCacheName, defaultCacheConfig.entryTtl(Duration.ofSeconds(userCacheExpireTime)));
    63. RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
    64. .cacheDefaults(defaultCacheConfig)
    65. .initialCacheNames(cacheNames)
    66. .withInitialCacheConfigurations(configMap)
    67. .build();
    68. return cacheManager;
    69. }
    70. }

    测试注解式开发,修改代码如下

    ClazzBiz.java:

    1. package com.ycx.spboot04.biz;
    2. import com.ycx.spboot04.model.Clazz;
    3. import com.ycx.spboot04.util.PageBean;
    4. import org.springframework.cache.annotation.CacheEvict;
    5. import org.springframework.cache.annotation.CachePut;
    6. import org.springframework.cache.annotation.Cacheable;
    7. import java.util.List;
    8. import java.util.Map;
    9. public interface ClazzBiz {
    10. // @CacheEvict(value = "xx",key = "'cid:'+#cid",allEntries = true)
    11. int deleteByPrimaryKey(Integer cid);
    12. int insert(Clazz record);
    13. int insertSelective(Clazz record);
    14. // @Cacheable(value = "test") ttl时间未60s
    15. @Cacheable(value = "clz",key="'cid:'+#cid")
    16. Clazz selectByPrimaryKey(Integer cid);
    17. int updateByPrimaryKeySelective(Clazz record);
    18. int updateByPrimaryKey(Clazz record);
    19. List<Clazz> listPager(Clazz clazz, PageBean pageBean);
    20. List<Map> listMapPager(Clazz clazz, PageBean pageBean);
    21. }

    ​​​​​​​

     

     今日知识到此结束,再见!

  • 相关阅读:
    智能座舱架构与芯片- (13) 软件篇 下
    android13 RK356X 预装第三方apk失败
    多通道振弦数据记录仪应用桥梁安全监测的解决方案
    java-net-php-python-Java奖助学金评审管理系统计算机毕业设计程序
    Jetson-XAVIAR NX 上编译tensorflow-lite
    logback-spring.xml 中根据不同的业务表示,分类打印到不同的文件夹、时区动态设置
    Cent OS 使用ip addr or nmcli 分配临时IP地址
    如何用WinRAR给压缩包设置和取消密码
    MFC 定时器使用
    太空射击第10课: Score (繪畫和文字)
  • 原文地址:https://blog.csdn.net/weixin_65808248/article/details/127650068