5.springboot整合其它项目

本文涉及的产品
云原生内存数据库 Tair,内存型 2GB
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Redis 版,经济版 1GB 1个月
简介: 5.springboot整合其它项目

个人博客地址: https://blog.zjzaki.com/archives/1691656689259

1.整合Druid


学习地址

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

1.1.Druid是什么

Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。

1.2.在哪里下载druid

1.3.怎么获取Druid的源码

Druid是一个开源项目,源码托管在github上,源代码仓库地址是 https://github.com/alibaba/druid 。同时每次Druid发布正式版本和快照的时候,都会把源码打包,你可以从上面的下载地址中找到相关版本的源码

1.4.添加pom依赖

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

1.5.application.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

1.6.启动项目

访问 http://localhost:8080/spboot04/druid

2.整合Redis


2.1.非注解式缓存

2.1.1.导入pom依赖

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

2.1.2.application.yml中添加配置

redis:
    host: 127.0.0.1
    password: 123465
    port: 6379
    database: 1

2.1.3.新建config包,添加RedisConfig.java

package com.zjzaki.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 zjzaki
 * @Package com.zjzaki.spboot04.config
 * @Date 2023-08-10 16:04:18
 */

@Configuration
public class RedisConfig {

    @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;
    }
}

2.1.4.service层ClazzBizImpl.java使用

添加

@Autowired
private RedisTemplate<String,Object> redisTemplate;

在修改listPager方法

@Override
public List<Clazz> listPager(Clazz clazz, PageBean pageBean) {
    List<Clazz> clzs = clazzMapper.listPager(clazz);
    redisTemplate.opsForValue().set("clz:1",clzs.get(0));
    redisTemplate.opsForValue().set("clzs",clzs);
    //        redisTemplate.opsForHash().entries()
    return clzs;
}

2.1.5.重启项目

访问地址: http://localhost:8080/spboot04/clz/list

在redis连接工具中查看

2.2.注解式缓存

2.2.1.修改RedisConfig.java的内容

package com.zjzaki.spboot04.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 zjzaki
 * @Package com.zjzaki.spboot04.config
 * @Date 2023-08-10 16:04:18
 */

@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;
    }
}

2.2.2.测试注解式开发

修改ClazzBiz.java的内容

@Cacheable(value = "redis-cache-clzs-",key = "'clzid:'+#cid")
Clazz selectByPrimaryKey(Integer cid);

ClazzController添加内容

@GetMapping("/select")
@ResponseBody
public Clazz selectByPrimaryKey(Integer cid){
    Clazz clazz = clazzBiz.selectByPrimaryKey(cid);
    return clazz;
}

请求http://localhost:8080/spboot04/clz/select?cid=2

查看redis中的内容

修改ClazzBiz.java的内容

@Cacheable(value = "test")
Clazz selectByPrimaryKey(Integer cid);

请求http://localhost:8080/spboot04/clz/select?cid=2

查看redis中的内容

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
9月前
|
druid Java 数据库连接
89.【SpringBoot-02】(九)
89.【SpringBoot-02】
63 0
|
9月前
|
存储 缓存 安全
89.【SpringBoot-02】(六)
89.【SpringBoot-02】
43 0
|
Kubernetes 负载均衡 网络协议
k8s中部署springboot项目
k8s中部署springboot项目
788 0
|
1月前
|
XML SQL Java
Springboot整合
Springboot整合
|
1月前
|
XML 开发框架 Java
【SpringBoot】什么是SpringBoot?简析SpringBoot
【SpringBoot】什么是SpringBoot?简析SpringBoot
17 1
|
1月前
|
Java
SpringBoot使用汇总
SpringBoot使用汇总
|
9月前
89.【SpringBoot-02】(七)
89.【SpringBoot-02】
26 0
|
9月前
|
Java
87.【SpringBoot-01】(九)
87.【SpringBoot-01】
52 0
|
10月前
|
前端开发 Java
简单项目【springboot】2
简单项目【springboot】2
22 0
|
10月前
|
Java
简单项目【springboot】1
简单项目【springboot】1
37 0