How to use spring-cache in spring cloud of Spring Cloud 2.x series

How to use spring-cache in spring cloud of Spring Cloud 2.x series

Learned how springcloud operates the database to add, delete, modify, and check, and learned how springcloud operates reids to store data in redis. Today, combined with database operations and reids operations, let's take a look at how to use SpringCache. SpringCache provides an annotation-based caching configuration method. It is essentially not a specific cache implementation scheme (such as EHCache), but an abstraction and encapsulation of the use of the cache. By adding a few predefined comments in the existing code, the desired cache effect can be achieved. SpringCache supports integration with third-party caches such as EHCache and Redis; in addition, it also provides a default implementation out of the box, which can be used directly. SpringCache supports the use of SpEL (Spring Expression Language) to define cache keys and various conditions, so it has considerable flexibility and can support very complex semantics.

 

1. Create a new project sc-redis-cache, the pom.xml file used is as follows

<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. Create a new springboot startup class 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);

}


}  

Remarks: @MapperScan(basePackages="sc.redis.cache.dao") The basePackages of this annotation must be the final registration of the package where the DAO is located.

If you write @MapperScan(basePackages="sc.redis.cache") like this, an error will be reported in the test:


3. Create a new configuration file 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 

Remarks: The configuration file contains the configuration information for connecting to the database and the configuration information for connecting to redis, and the log level of the print sql statement is configured at the same time


4. Create a new custom reids serialization method RedisCacheSerializeConfiguration.java class

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. Please refer to the source code to start related classes, the directory structure is as follows


6. Write unit test classes

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. Perform unit testing

Run the add method to add a piece of data to the database:

Log:


Run the get method for the first time:

Log:


Use redis-cli to view redis, the data has been inserted into the cache


Run the get method for the second time:

Log:


It was found that no sql statement was printed, indicating that the data was obtained from redis, and no data was queried in the database.

Source code:

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

Author: java Paradise

This article is from Yunqi Community s partner " java Paradise ". For relevant information, please pay attention to " java Paradise "