20、springcloud如何使用spring-cache


學了springcloud如何操作數據庫進行增刪改查,又學了springcloud如何操作reids把數據存儲到redis。今天結合數據庫操作和reids操作,來看看如何使用SpringCacheSpringCache提供了基於注解的緩存配置方法。它本質上不是一個具體的緩存實現方案(例如EHCache),而是一個對緩存使用的抽象和封裝,通過在已有代碼中打上幾個預定義的注釋,就可以實現希望達到的緩存效果。SpringCache支持跟第三方緩存例如EHCacheRedis集成;另外也提供了開箱即用的默認實現,可以直接拿來使用。SpringCache支持使用SpELSpring Expression Language)來定義緩存的key和各種condition,因此具備相當的靈活性,並可以支持非常復雜的語義。

 

1、 新建項目sc-redis-cache,對用的pom.xml文件如下

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

 

<groupId>spring-cloud</groupId>

<artifactId>sc-redis-cache</artifactId>

<version>0.0.1-SNAPSHOT</version>

<packaging>jar</packaging>

 

<name>sc-redis-cache</name>

<url>http://maven.apache.org</url>

 

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.0.4.RELEASE</version>

</parent>

 

<dependencyManagement>

<dependencies>

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-dependencies</artifactId>

<version>Finchley.RELEASE</version>

<type>pom</type>

<scope>import</scope>

</dependency>

 

</dependencies>

</dependencyManagement>

 

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<maven.compiler.source>1.8</maven.compiler.source>

<maven.compiler.target>1.8</maven.compiler.target>

</properties>

 

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-pool2</artifactId>

</dependency>

 

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

 

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-cache</artifactId>

</dependency>

 

<dependency>

<groupId>com.zaxxer</groupId>

<artifactId>HikariCP</artifactId>

</dependency>

 

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>6.0.3</version>

</dependency>

 

 

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis-spring</artifactId>

<version>1.3.2</version>

</dependency>

 

<dependency>

<groupId>org.mybatis.spring.boot</groupId>

<artifactId>mybatis-spring-boot-starter</artifactId>

<version>1.3.2</version>

</dependency>

 

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

</project>

 

 

2、 新建springboot啟動類RedisCacheApplication.java

 

package sc.redis.cache;

 

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cache.annotation.EnableCaching;

 

/**

 * 更多資源關注公眾號: java樂園

 *

 * @author Administrator

 *

 */

@SpringBootApplication

@EnableCaching // 啟動緩存

@MapperScan(basePackages="sc.redis.cache.dao")

public class RedisCacheApplication {

 

public static void main(String[] args) {

SpringApplication.run(RedisCacheApplication.class, args);

}

 

}

 

 

備注:@MapperScan(basePackages="sc.redis.cache.dao")該注解的basePackages一定是DAO所在包最終報名。

如果寫成@MapperScan(basePackages="sc.redis.cache ")這樣在測試中將報錯:

 

 

 

 

3、 新建配置文件application.yml

 

server:

  port: 9003

  

spring:

  application:

    name: sc-redis-cache

  datasource:

    driverClassName: com.mysql.jdbc.Driver

    url: jdbc:mysql://localhost:3306/sc?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8

    username: root

    password: root

    type: com.zaxxer.hikari.HikariDataSource

    hikari:

      minimum-idle: 5

      maximum-pool-size: 15

      auto-commit: true

      idle-timeout: 30000

      pool-name: DatebookHikariCP

      max-lifetime: 1800000

      connection-timeout: 30000

      connection-test-query: SELECT 1

  cache:

    type: REDIS

    redis:

      timeToLive: 200000 #緩存超時時間ms

      cache-null-values: false #是否緩存空值

  redis:

    host: 127.0.0.1

    password:

    port: 6379

    timeout: 10000 # 連接超時時間(毫秒)

    database: 0 # Redis默認情況下有16個分片,這里配置具體使用的分片,默認是0

    lettuce:

      pool:

        max-active: 8 # 連接池最大連接數(使用負值表示沒有限制) 默認 8

        max-wait: -1 # 連接池最大阻塞等待時間(使用負值表示沒有限制) 默認 -1

        max-idle: 8 # 連接池中的最大空閑連接 默認 8

        min-idle: 0 # 連接池中的最小空閑連接 默認 0

 

logging:

  level:

    sc.redis.cache.dao: debug

 

 

備注:配置文件中有連接數據庫的配置信息和連接redis的配置信息,同時配置了打印sql語句的日志級別

 

 

 

 

4、 新建自定義reids序列化方式RedisCacheSerializeConfiguration.java

 

package sc.redis.cache.config;

 

import java.time.Duration;

 

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.serializer.GenericJackson2JsonRedisSerializer;

import org.springframework.data.redis.serializer.RedisSerializationContext;

import org.springframework.data.redis.serializer.RedisSerializer;

import org.springframework.data.redis.serializer.StringRedisSerializer;

 

@Configuration

public class RedisCacheSerializeConfiguration {

 

// /**

//  *二選一

//  * 設置 redis 數據默認過期時間 設置@cacheable 序列化方式

//  *

//  * @return

//  */

// @Bean

// public RedisCacheConfiguration redisCacheConfiguration() {

// RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();

// configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))

// .entryTtl(Duration.ofDays(30));

// configuration.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()));

// return configuration;

// }

 

/**

 * 二選一

 * 設置 redis 數據默認過期時間 設置@cacheable 序列化方式

 *

 * @param connectionFactory

 * @return

 */

@Bean

public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {

RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(30))

.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))

.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))

.disableCachingNullValues();

RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory).cacheDefaults(config)

.transactionAware().build();

System.out.println("自定義RedisCacheManager加載完成");

return redisCacheManager;

}

 

private RedisSerializer<String> keySerializer() {

return new StringRedisSerializer();

}

 

private RedisSerializer<Object> valueSerializer() {

return new GenericJackson2JsonRedisSerializer();

}

 

}

 

5、 啟動相關類請參照源碼,目錄結構如下

 

 

 

6、 編寫單元測試類

 

package sc.redis.cache;

 

import org.junit.Test;

import org.junit.runner.RunWith;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.test.context.junit4.SpringRunner;

 

import sc.redis.cache.model.User;

import sc.redis.cache.service.UserService;

 

@RunWith(SpringRunner.class)

@SpringBootTest

public class TestRedis {

 

private static final Logger logger = LoggerFactory.getLogger(TestRedis.class);

 

@Autowired

private UserService userService;

 

@Test

public void add() {

User u = new User();

u.setId(4L);

u.setUserName("huangjinjin");

u.setPosition("cto");

u.setAge(24);

userService.addUser(u);

 

}

 

@Test

public void get() {

User u =userService.getUser(4L);

logger.debug("userName = "+ u.getUserName());

}

}

 

7、 進行單元測試

運行add方法添加一條數據到數據庫:

日志:

 

 

 

第一次運行get方法:

日志:

  

 

 

使用redis-cli查看redis,數據已經插入緩存

 

 

 

第二次運行get方法:

日志:

 

 

 

發現沒有打印任何sql語句,說明數據是從redis獲取的,沒有去數據庫查詢數據。

 

https://gitee.com/hjj520/spring-cloud-2.x


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM