首頁 >資料庫 >Redis >SpringBoot如何整合Druid、Redis

SpringBoot如何整合Druid、Redis

王林
王林轉載
2023-05-31 22:31:18992瀏覽

1.整合Druid

1.1Druid簡介

Java程式很大一部分要操作資料庫,為了提高效能操作資料庫的時候,又得使用資料庫連線池。

Druid 是阿里巴巴開源平台上一個資料庫連接池實現,結合了 C3P0、DBCP 等 DB 池的優點,同時加入了日誌監控。

Druid是專為監控而生的資料庫連線池,能夠有效監控資料庫連線池的連線情況和SQL執行情況。

1.2新增上 Druid 資料來源依賴

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

1.3使用Druid 資料來源

server:
  port: 8080
spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/eshop?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true
      username: xxx
      password: xxx
      driver-class-name: com.mysql.cj.jdbc.Driver
      initial-size: 10
      max-active: 20
      min-idle: 10
      max-wait: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      stat-view-servlet:
        enabled: true
        login-username: admin
        login-password: 1234
logging:
  level:
    com.wyy.spring.Dao: debug

測試一下看是否成功!

package com.wyy.spring;
import com.wyy.spring.Dao.StudentMapper;
import com.wyy.spring.service.StudentService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
@SpringBootTest
class SpringBoot04ApplicationTests {
    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() {
        System.out.println(dataSource.getClass());
    }
}

列印結果 

SpringBoot如何整合Druid、Redis

# 2.整合redis

2.1新增上redis依賴

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

2.2 yml新增redis設定資訊 

redis:
    database: 0
    host: 120.0.0.0
    port: 6379
    password: xxxx
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
    timeout: 10000

2.3 redis 設定類別 

package com.wyy.spring.conf;
 
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
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.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.ClassUtils;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.time.Duration;
@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {
    @Bean
    @Primary
    /**
     * 缓存管理器
     */
    CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .computePrefixWith(cacheName -> cacheName + ":-cache-:")
                /*设置缓存过期时间*/
                .entryTtl(Duration.ofHours(1))
                /*禁用缓存空值,不缓存null校验*/
                .disableCachingNullValues()
                /*设置CacheManager的值序列化方式为json序列化,可使用加入@Class属性*/
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(
                        new GenericJackson2JsonRedisSerializer()
                ));
        /*使用RedisCacheConfiguration创建RedisCacheManager*/
        RedisCacheManager manager = RedisCacheManager.builder(factory)
                .cacheDefaults(cacheConfiguration)
                .build();
        return manager;
    }
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(factory);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        /* key序列化 */
        redisTemplate.setKeySerializer(stringSerializer);
        /* value序列化 */
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        /* Hash key序列化 */
        redisTemplate.setHashKeySerializer(stringSerializer);
        /* Hash value序列化 */
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    @Override
    public KeyGenerator keyGenerator() {
        return (Object target, Method method, Object... params) -> {
            final int NO_PARAM_KEY = 0;
            final int NULL_PARAM_KEY = 53;
            StringBuilder key = new StringBuilder();
            /* Class.Method: */
            key.append(target.getClass().getSimpleName())
                    .append(".")
                    .append(method.getName())
                    .append(":");
            if (params.length == 0) {
                return key.append(NO_PARAM_KEY).toString();
            }
            int count = 0;
            for (Object param : params) {
                /* 参数之间用,进行分隔 */
                if (0 != count) {
                    key.append(&#39;,&#39;);
                }
                if (param == null) {
                    key.append(NULL_PARAM_KEY);
                } else if (ClassUtils.isPrimitiveArray(param.getClass())) {
                    int length = Array.getLength(param);
                    for (int i = 0; i < length; i++) {
                        key.append(Array.get(param, i));
                        key.append(&#39;,&#39;);
                    }
                } else if (ClassUtils.isPrimitiveOrWrapper(param.getClass()) || param instanceof String) {
                    key.append(param);
                } else {
                    /*JavaBean一定要重写hashCode和equals*/
                    key.append(param.hashCode());
                count++;
            return key.toString();
        };
}

@CacheConfig 一個類別層級的註解,允許共用快取的cacheNames、KeyGenerator、CacheManager 與CacheResolver

@CacheableNames、KeyGenerator、CacheManager 和CacheResolver

##@Cacheable用來聲明方法是可快取的。將執行過的方法的結果緩存,以便在後續使用相同參數呼叫時不需要再次執行實際的方法。直接從快取中取值

@CachePut 標註的方法在執行前不會去檢查快取中是否存在之前執行過的結果,而是每次都會執行該方法, 並將執行結果以鍵值對的形式存入指定的快取中。

@CacheEvict 的角色 主要針對方法配置,能夠依照一定的條件對快取進行清空 ###

以上是SpringBoot如何整合Druid、Redis的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除