0 环境
系统环境:win10
编辑器:IDEA
1 前言->环境搭建
1-1 pom依赖
<?xml version="1.0" encoding="UTF-8"?> <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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.8.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>org.javaboy</groupId> <artifactId>chapter09-cacheredis</artifactId> <version>0.0.1-SNAPSHOT</version> <name>chapter09-cacheredis</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
1-2 properties(redis的基本配置以及缓存名的配置)
spring.redis.host=127.0.0.1 spring.redis.password=123456 spring.redis.port=6379 spring.redis.database=0 spring.cache.cache-names=c1
1-3 Application启动项添加
1-4 自定义KeyGenerator
@Component public class MyKeyGen implements KeyGenerator { @Override public Object generate(Object o, Method method, Object... objects) { return method.getName()+":"+ Arrays.toString(objects); }
1-5 service层
@Service //@CacheConfig(cacheNames = "c1") public class BookService { // key = "#methodName" // key = "#method.name" // key = "#caches[0]" // key = "#args[0]" // @Cacheable(cacheNames = "c1",key = "#caches[0]") @Cacheable(cacheNames = "c1",key = "'myKeyGen'") public Book getUserById(Integer id){ System.out.println("book>>>>>>" + id); Book book = new Book(); book.setId(id); return book; } }
1-6 单元测试
@Autowired BookService bookService; @Test public void contextLoads() { Book book = bookService.getUserById(1); Book book1 = bookService.getUserById(1); System.err.println("book --->>" + book); System.err.println("book1 --->>" + book1); }
2 报错
key = "''" (需要内嵌一下单引号 不然会报错)