学了springcloud如何操作数据库进行增删改查,又学了springcloud如何操作reids把数据存储到redis。今天结合数据库操作和reids操作,来看看如何使用SpringCache。SpringCache提供了基于注解的缓存配置方法。它本质上不是一个具体的缓存实现方案(例如EHCache),而是一个对缓存使用的抽象和封装,通过在已有代码中打上几个预定义的注释,就可以实现希望达到的缓存效果。SpringCache支持跟第三方缓存例如EHCache、Redis集成;另外也提供了开箱即用的默认实现,可以直接拿来使用。SpringCache支持使用SpEL(Spring 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