天天看點

Spring Cloud 2.x系列之springcloud如何使用spring-cache

學了springcloud如何操作資料庫進行增删改查,又學了springcloud如何操作reids把資料存儲到redis。今天結合資料庫操作和reids操作,來看看如何使用SpringCache。SpringCache提供了基于注解的緩存配置方法。它本質上不是一個具體的緩存實作方案(例如EHCache),而是一個對緩存使用的抽象和封裝,通過在已有代碼中打上幾個預定義的注釋,就可以實作希望達到的緩存效果。SpringCache支援跟第三方緩存例如EHCache、Redis內建;另外也提供了開箱即用的預設實作,可以直接拿來使用。SpringCache支援使用SpEL(Spring ExpressionLanguage)來定義緩存的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.0http://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")這樣在測試中将報錯:

Spring Cloud 2.x系列之springcloud如何使用spring-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語句的日志級别

Spring Cloud 2.x系列之springcloud如何使用spring-cache

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

publicclass RedisCacheSerializeConfiguration{



///**

// *二選一

// * 設定 redis資料預設過期時間設定@cacheable序列化方式

// *

// * @return

// */

//@Bean

//public RedisCacheConfiguration redisCacheConfiguration() {

//    RedisCacheConfigurationconfiguration = 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) {

      RedisCacheConfigurationconfig = 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加載完成");

      returnredisCacheManager;

   }

   private RedisSerializer<String> keySerializer() {

      returnnewStringRedisSerializer();

   }


   private RedisSerializer<Object> valueSerializer() {

      returnnewGenericJackson2JsonRedisSerializer();

   }


}           

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

Spring Cloud 2.x系列之springcloud如何使用spring-cache

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

publicclass TestRedis {



   privatestaticfinal Logger logger =LoggerFactory.getLogger(TestRedis.class);



   @Autowired

   privateUserService userService;



   @Test

   publicvoid add() {

      User u = new User();

      u.setId(4L);

      u.setUserName("huangjinjin");

      u.setPosition("cto");

      u.setAge(24);

      userService.addUser(u);


   }


   @Test

   publicvoid get() {

      User u =userService.getUser(4L);

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

   }

}           

7、進行單元測試

運作add方法添加一條資料到資料庫:

日志:

Spring Cloud 2.x系列之springcloud如何使用spring-cache

第一次運作get方法:

Spring Cloud 2.x系列之springcloud如何使用spring-cache

使用redis-cli檢視redis,資料已經插入緩存

Spring Cloud 2.x系列之springcloud如何使用spring-cache

第二次運作get方法:

Spring Cloud 2.x系列之springcloud如何使用spring-cache

發現沒有列印任何sql語句,說明資料是從redis擷取的,沒有去資料庫查詢資料。

源碼:

https://gitee.com/hjj520/spring-cloud-2.x/tree/master/sc-redis-cache           

本文作者:java樂園

本文來自雲栖社群合作夥伴“

java樂園

”,了解相關資訊可以關注“