SpringBoot(5)-SpringBoot整合其他项目

1.整合Druid数据库连接池

1.1学习地址

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

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

 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

1.2application.yml

mybatis:
  mapper-locations: classpath:mappers/**/*.xml
  type-aliases-package: com.hyx.springboot04.entity
logging:
  level:
    com.hyx.springboot04: debug
server:
  port: 8080
  servlet:
    context-path: /springboot04
spring:
  application:
    name: springboot04
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    name: defaultDataSource
    password: 123456
    url: jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=UTF-8
    username: root
    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
  freemarker:
    cache: false
    charset: utf-8
    expose-request-attributes: true
    expose-session-attributes: true
    suffix: .ftl
    template-loader-path: classpath:/templates/
  resources:
    static-locations: classpath:/static/**
pagehelper:
  reasonable: true
  supportMethodsArguments: true
  page-size-zero: true
  helper-dialect: mysql

image-20230810215140832

1.3访问一下

image-20230810215703470

输入密码,来到我们的监控平台

image-20230810215739754

SQL监控

image-20230810215921373

1.4随便执行一下新增

image-20230810220019350

image-20230810220127186

也能点进来看到执行SQL的时间和语句

image-20230810220223182

2.整合Redis

2.1添加redis pom依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2.2打开redis服务

image-20230810221929139

2.3添加redis application.yml 依赖

mybatis:
  mapper-locations: classpath:mappers/**/*.xml
  type-aliases-package: com.hyx.springboot04.entity
logging:
  level:
    com.hyx.springboot04: debug
server:
  port: 8080
  servlet:
    context-path: /springboot04
spring:
  application:
    name: springboot04
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    name: defaultDataSource
    password: 123456
    url: jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=UTF-8
    username: root
    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
  freemarker:
    cache: false
    charset: utf-8
    expose-request-attributes: true
    expose-session-attributes: true
    suffix: .ftl
    template-loader-path: classpath:/templates/
  redis:
    host: localhost
    password: 123456
    port: 6379
    database: 8
  resources:
    static-locations: classpath:/static/**
pagehelper:
  reasonable: true
  supportMethodsArguments: true
  page-size-zero: true
  helper-dialect: mysql

2.4修改redis密码(非必须)

image-20230810222424877

redis修改密码(我这里没有设置密码,去掉application.yml中的redis password配置)

修改

image-20230810224143196

image-20230810222820734

redis直接存汉字会乱码,需要序列化

2.5biz/impl/ClazzBiz自动装配

image-20230810223544123

2.6biz/impl/ClazzBiz自动装配修改代码测试数据是否被缓存

image-20230810223613622

image-20230810225034968

2.7改造biz/impl/ClazzBiz.java的代码

    @Override
    public List<Clazz> listPager(Clazz clazz, PageBean pageBean) {
        //先从缓存拿数据
        List<Clazz> clazzes =(List<Clazz>)redisTemplate.opsForValue().get("clzs");
        //如果缓存中数据为空
        if(clazzes==null){
            //直接查数据库
            clazzes = clazzMapper.listPager(clazz);
            //返回之前将数据库中的数据写入缓存
            redisTemplate.opsForValue().set("clzs",clazzes);
        }
        return clazzes;
    }

image-20230810230140476

2.8测试查询列表

image-20230810230319487

image-20230810230225001

image-20230810230301244

可见,通过redis的缓存可以减少查询数据库,降低数据库的压力

3.Redis注解式开发

非关系型数据库

redis:基于内存的

ehcache 基于文件的

mongodb 基于文档的

3.1修改RedisConfig

package com.hyx.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;

@EnableCaching
@Configuration
public class RedisConfig {
    private final int defaultExpireTime = 600;

    private final int userCacheExpireTime = 60;

    private final String userCacheName = "test";
    @Bean
    public RedisTemplate<String,Object> getRedisTemplate(RedisConnectionFactory connectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
//        redisTemplate.afterPropertiesSet();

        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<String> cacheNames = new HashSet<>();
        cacheNames.add(userCacheName);

        // 对每个缓存空间应用不同的配置
        Map<String, RedisCacheConfiguration> 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;
    }
}

image-20230810235424757

3.2在RedisController中写一个方法

    @ResponseBody
    @RequestMapping("/load")
    public Clazz load(int cid){
        return clazzBiz.selectByPrimaryKey(cid);
    }

3.3测试

image-20230810235319115

image-20230811000306560

3.4 将注解值改为“test”,缓存存活时间变了,也就是说我们可以根据不同的缓存设置不同的过期时间

image-20230811000516183

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值