导入依赖
< 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- web< / artifactId>
< / dependency>
< dependency>
< groupId> org. springframework. boot< / groupId>
< artifactId> spring- boot- starter- test< / artifactId>
< scope> test< / scope>
< / dependency>
< / dependencies>
配置application.properties文件
spring. redis. host= 192.168 .65 .128
spring. redis. port= 6379
spring. redis. password= hx
在model包下创建User类
package org. hx. springboot_cache_demo42. model;
import java. io. Serializable;
public class User implements Serializable {
private Integer id;
private String username;
public Integer getId ( ) {
return id;
}
public void setId ( Integer id) {
this . id = id;
}
public String getUsername ( ) {
return username;
}
public void setUsername ( String username) {
this . username = username;
}
}
在Service包下创建UserService类
package org. hx. springboot_cache_demo42. Service;
import org. hx. springboot_cache_demo42. model. User;
import org. springframework. cache. annotation. Cacheable;
import org. springframework. stereotype. Service;
@Service
public class UserService {
@Cacheable ( cacheNames = "c2" )
public User getUserById ( Integer id) {
System. out. println ( "getUserById: " + id) ;
User user = new User ( ) ;
user. setId ( id) ;
user. setUsername ( "hx" ) ;
return user;
}
}
在启动类中添加@EnableCaching标签,开启缓存功能
package org. hx. springboot_cache_demo42;
import org. springframework. boot. SpringApplication;
import org. springframework. boot. autoconfigure. SpringBootApplication;
import org. springframework. cache. annotation. EnableCaching;
@SpringBootApplication
@EnableCaching
public class SpringbootCacheDemo42Application {
public static void main ( String[ ] args) {
SpringApplication. run ( SpringbootCacheDemo42Application. class , args) ;
}
}
在单元测试类中进行测试
package org. hx. springboot_cache_demo42;
import org. hx. springboot_cache_demo42. Service. UserService;
import org. hx. springboot_cache_demo42. model. User;
import org. junit. jupiter. api. Test;
import org. springframework. beans. factory. annotation. Autowired;
import org. springframework. boot. test. context. SpringBootTest;
@SpringBootTest
class SpringbootCacheDemo42ApplicationTests {
@Autowired
UserService userService;
@Test
void contextLoads ( ) {
for ( int i = 0 ; i < 3 ; i++ ) {
User u = userService. getUserById ( 99 ) ;
System. out. println ( "u = " + u) ;
}
}
}
当redis缓存中没有当前数据时,进行数据添加,如果redis缓存中存在当前数据,则直接读取。