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

springboot整合其它项目_第1张图片

用户名和密码对应如下: 

 springboot整合其它项目_第2张图片

springboot整合其它项目_第3张图片

 springboot整合其它项目_第4张图片

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

 (SQL监控也能看到)springboot整合其它项目_第5张图片

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

pom.xml:


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

 yml配置:

mybatis:
    mapper-locations: classpath:mappers/*xml
    type-aliases-package: com.ycx.spboot04.model
server:
    port: 8080
    servlet:
        context-path: /spboot04
spring:
    application:
        name: spboot04
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        name: defaultDataSource
        password: 1234
        url: jdbc:mysql://localhost:3306/yjy?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/# 应用服务 WEB 访问端口
    mvc:
        static-path-pattern: /static/**
    redis:
        host:192.168.122.128
    password: 
        port: 6379
        database: 0
    pagehelper:
        reasonable: true
        supportMethodsArguments: true
        page-size-zero: true
        helper-dialect: mysql
#logging:
#    level:
#        com.ycx.spboot04:debug

RedisConfig :

package com.ycx.spboot04.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 杨总
 * @create 2022-11-02 22:03
 *
 * @Configuration:凡是被@Configuration注解所标记,就代表当前这个类为配置类
 * 而配置类等价于ssm阶段中spring-*.xml这一类的配置文件
 *
 * spring-*.xml
 * 
 * 将redistemplate进行配置,然后交给spring进行管理
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate getRedisTemplate(RedisConnectionFactory connectionFactory){
        RedisTemplate redisTemplate=new RedisTemplate<>();

//        配置序列化器
        //针对于key
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        //针对于value
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
//        redisTemplate.afterPropertiesSet();//根据不同的redis版本

        //  connectionFactory是包含了redis的连接信息
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;

    }

}

 ClazzBizImpl :

package com.ycx.spboot04.biz.impl;

import com.ycx.spboot04.biz.ClazzBiz;
import com.ycx.spboot04.mapper.ClazzMapper;
import com.ycx.spboot04.model.Clazz;
import com.ycx.spboot04.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;


@Service
public class ClazzBizImpl implements ClazzBiz {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public int deleteByPrimaryKey(Integer cid) {
        System.out.println("不做任何操作...");
        return clazzMapper.deleteByPrimaryKey(cid);
//        return 0;
    }

    @Override
    public int insert(Clazz record) {
        return clazzMapper.insert(record);
    }

    @Override
    public int insertSelective(Clazz record) {
        return clazzMapper.insertSelective(record);
    }

    @Override
    public Clazz selectByPrimaryKey(Integer cid) {
        return clazzMapper.selectByPrimaryKey(cid);
    }

    @Override
    public int updateByPrimaryKeySelective(Clazz record) {
        return clazzMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Clazz record) {
        return clazzMapper.updateByPrimaryKey(record);
    }

    @Override
    public List listPager(Clazz clazz, PageBean pageBean) {
        List clazzes = clazzMapper.listPager(clazz);
        //       将班级信息缓存到redis中
        redisTemplate.opsForValue().set("clz_infos",clazzes);
        return clazzes;
    }

    @Override
    public List listMapPager(Clazz clazz, PageBean pageBean) {
        if(true)
            throw new RuntimeException("查询班级信息异常,异常存在于ClazzBizImpl.list。。。。");
        return clazzMapper.listMapPager(clazz);
    }
}

 springboot整合其它项目_第6张图片

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

springboot整合其它项目_第7张图片

 

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

注解式缓存

RedisConfig :

package com.ycx.spboot04.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 杨总
 * @create 2022-11-02 22:03
 *
 * @Configuration:凡是被@Configuration注解所标记,就代表当前这个类为配置类
 * 而配置类等价于ssm阶段中spring-*.xml这一类的配置文件
 *
 * spring-*.xml
 * 
 * 将redistemplate进行配置,然后交给spring进行管理
 */
@Configuration
public class RedisConfig {
    private final int defaultExpireTime = 600;

    private final int userCacheExpireTime = 60;

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

//        配置序列化器
        //针对于key
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        //针对于value
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(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;
    }
}

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

ClazzBiz.java:

package com.ycx.spboot04.biz;

import com.ycx.spboot04.model.Clazz;
import com.ycx.spboot04.util.PageBean;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

import java.util.List;
import java.util.Map;

public interface ClazzBiz {
//    @CacheEvict(value = "xx",key = "'cid:'+#cid",allEntries = true)
    int deleteByPrimaryKey(Integer cid);

    int insert(Clazz record);

    int insertSelective(Clazz record);


//    @Cacheable(value = "test") ttl时间未60s
    @Cacheable(value = "clz",key="'cid:'+#cid")
    Clazz selectByPrimaryKey(Integer cid);

    int updateByPrimaryKeySelective(Clazz record);

    int updateByPrimaryKey(Clazz record);

    List listPager(Clazz clazz, PageBean pageBean);
    List listMapPager(Clazz clazz, PageBean pageBean);
}

​​​​​​​springboot整合其它项目_第8张图片

 

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

你可能感兴趣的:(spring,boot,java,spring)