1.安装redis
a.由于官方是没有Windows版的,所以我们需要下载微软开发的redis,网址:https://github.com/MicrosoftArchive/redis/releases
b.解压后,在redis根目录打开cmd界面,输入:redis-server.exe redis.windows.conf,启动redis(关闭cmd窗口即停止)
2.使用
a.创建SpringBoot工程,选择maven依赖
1<dependencies> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-starter-web</artifactId> 5 </dependency> 6 <dependency> 7 <groupId>org.springframework.boot</groupId> 8 <artifactId>spring-boot-starter-thymeleaf</artifactId> 9 </dependency> 10 <dependency> 11 <groupId>org.springframework.boot</groupId> 12 <artifactId>spring-boot-starter-data-redis</artifactId> 13 </dependency> 14 15 ..... 16 17 </dependencies>
b.配置 application.yml 配置文件
1server: 2 port: 8080 3spring: 4 # redis相关配置 5 redis: 6 database: 0 7 host: localhost 8 port: 6379 9 password: 10 jedis: 11 pool: 12 # 连接池最大连接数(使用负值表示没有限制) 13 max-active: 8 14 # 连接池最大阻塞等待时间(使用负值表示没有限制) 15 max-wait: -1ms 16 # 连接池中的最大空闲连接 17 max-idle: 5 18 # 连接池中的最小空闲连接 19 min-idle: 0 20 # 连接超时时间(毫秒)默认是2000ms 21 timeout: 2000ms 22 # thymeleaf热更新 23 thymeleaf: 24 cache: false
c.创建RedisConfig配置类
1@Configuration 2@EnableCaching //开启缓存 3public class RedisConfig { 4 5 /** 6 * 缓存管理器 7 * @param redisConnectionFactory 8 * @return 9 */ 10 @Bean 11 public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { 12 // 生成一个默认配置,通过config对象即可对缓存进行自定义配置 13 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); 14 // 设置缓存的默认过期时间,也是使用Duration设置 15 config = config.entryTtl(Duration.ofMinutes(30)) 16 // 设置 key为string序列化 17 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) 18 // 设置value为json序列化 19 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer())) 20 // 不缓存空值 21 .disableCachingNullValues(); 22 23 // 对每个缓存空间应用不同的配置 24 Map<String, RedisCacheConfiguration> configMap = new HashMap<>(); 25 configMap.put("userCache", config.entryTtl(Duration.ofSeconds(60))); 26 27 // 使用自定义的缓存配置初始化一个cacheManager 28 RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory) 29 //默认配置 30 .cacheDefaults(config) 31 // 特殊配置(一定要先调用该方法设置初始化的缓存名,再初始化相关的配置) 32 .initialCacheNames(configMap.keySet()) 33 .withInitialCacheConfigurations(configMap) 34 .build(); 35 return cacheManager; 36 } 37 38 /** 39 * Redis模板类redisTemplate 40 * @param factory 41 * @return 42 */ 43 @Bean 44 public RedisTemplate redisTemplate(RedisConnectionFactory factory) { 45 RedisTemplate<String, Object> template = new RedisTemplate<>(); 46 template.setConnectionFactory(factory); 47 // key采用String的序列化方式 48 template.setKeySerializer(new StringRedisSerializer()); 49 // hash的key也采用String的序列化方式 50 template.setHashKeySerializer(new StringRedisSerializer()); 51 // value序列化方式采用jackson 52 template.setValueSerializer(jackson2JsonRedisSerializer()); 53 // hash的value序列化方式采用jackson 54 template.setHashValueSerializer(jackson2JsonRedisSerializer()); 55 return template; 56 } 57 58 /** 59 * json序列化 60 * @return 61 */ 62 private RedisSerializer<Object> jackson2JsonRedisSerializer() { 63 //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值 64 Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class); 65 //json转对象类,不设置默认的会将json转成hashmap 66 ObjectMapper mapper = new ObjectMapper(); 67 mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 68 mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 69 serializer.setObjectMapper(mapper); 70 return serializer; 71 } 72 73}
d.创建entity实体类
1public class User implements Serializable { 2 3 private int id; 4 private String userName; 5 private String userPwd; 6 7 public User(){} 8 9 public User(int id, String userName, String userPwd) { 10 this.id = id; 11 this.userName = userName; 12 this.userPwd = userPwd; 13 } 14 15 public int getId() { 16 return id; 17 } 18 19 public void setId(int id) { 20 this.id = id; 21 } 22 23 public String getUserName() { 24 return userName; 25 } 26 27 public void setUserName(String userName) { 28 this.userName = userName; 29 } 30 31 public String getUserPwd() { 32 return userPwd; 33 } 34 35 public void setUserPwd(String userPwd) { 36 this.userPwd = userPwd; 37 } 38 39}
e.创建Service
1@Service 2public class UserService { 3 4 //查询:先查缓存是是否有,有则直接取缓存中数据,没有则运行方法中的代码并缓存 5 @Cacheable(value = "userCache", key = "'user:' + #userId") 6 public User getUser(int userId) { 7 System.out.println("执行此方法,说明没有缓存"); 8 return new User(userId, "用户名(get)_" + userId, "密码_" + userId); 9 } 10 11 //添加:运行方法中的代码并缓存 12 @CachePut(value = "userCache", key = "'user:' + #user.id") 13 public User addUser(User user){ 14 int userId = user.getId(); 15 System.out.println("添加缓存"); 16 return new User(userId, "用户名(add)_" + userId, "密码_" + userId); 17 } 18 19 //删除:删除缓存 20 @CacheEvict(value = "userCache", key = "'user:' + #userId") 21 public boolean deleteUser(int userId){ 22 System.out.println("删除缓存"); 23 return true; 24 } 25 26 @Cacheable(value = "common", key = "'common:user:' + #userId") 27 public User getCommonUser(int userId) { 28 System.out.println("执行此方法,说明没有缓存(测试公共配置是否生效)"); 29 return new User(userId, "用户名(common)_" + userId, "密码_" + userId); 30 } 31 32}
f.创建Controller
1@RestController 2@RequestMapping("/user") 3public class UserController { 4 5 @Resource 6 private UserService userService; 7 8 @RequestMapping("/getUser") 9 public User getUser(int userId) { 10 return userService.getUser(userId); 11 } 12 13 @RequestMapping("/addUser") 14 public User addUser(User user){ 15 return userService.addUser(user); 16 } 17 18 @RequestMapping("/deleteUser") 19 public boolean deleteUser(int userId){ 20 return userService.deleteUser(userId); 21 } 22 23 @RequestMapping("/getCommonUser") 24 public User getCommonUser(int userId) { 25 return userService.getCommonUser(userId); 26 } 27 28} 29 30@Controller 31public class HomeController { 32 //默认页面 33 @RequestMapping("/") 34 public String login() { 35 return "test"; 36 } 37 38}
g.在 templates 目录下,写书 test.html 页面
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <title>test</title> 6 <style type="text/css"> 7 .row{ 8 margin:10px 0px; 9 } 10 .col{ 11 display: inline-block; 12 margin:0px 5px; 13 } 14 </style> 15</head> 16<body> 17<div> 18 <h1>测试</h1> 19 <div class="row"> 20 <label>用户ID:</label><input id="userid-input" type="text" name="userid"/> 21 </div> 22 <div class="row"> 23 <div class="col"> 24 <button id="getuser-btn">获取用户</button> 25 </div> 26 <div class="col"> 27 <button id="adduser-btn">添加用户</button> 28 </div> 29 <div class="col"> 30 <button id="deleteuser-btn">删除用户</button> 31 </div> 32 <div class="col"> 33 <button id="getcommonuser-btn">获取用户(common)</button> 34 </div> 35 </div> 36 <div class="row" id="result-div"></div> 37</div> 38</body> 39<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 40<script> 41 $(function() { 42 $("#getuser-btn").on("click",function(){ 43 var userId = $("#userid-input").val(); 44 $.ajax({ 45 url: "/user/getUser", 46 data: { 47 userId: userId 48 }, 49 dataType: "json", 50 success: function(data){ 51 $("#result-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]"); 52 }, 53 error: function(e){ 54 $("#result-div").text("系统错误!"); 55 }, 56 }) 57 }); 58 $("#adduser-btn").on("click",function(){ 59 var userId = $("#userid-input").val(); 60 $.ajax({ 61 url: "/user/addUser", 62 data: { 63 id: userId 64 }, 65 dataType: "json", 66 success: function(data){ 67 $("#result-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]"); 68 }, 69 error: function(e){ 70 $("#result-div").text("系统错误!"); 71 }, 72 }) 73 }); 74 $("#deleteuser-btn").on("click",function(){ 75 var userId = $("#userid-input").val(); 76 $.ajax({ 77 url: "/user/deleteUser", 78 data: { 79 userId: userId 80 }, 81 dataType: "json", 82 success: function(data){ 83 $("#result-div").text(data); 84 }, 85 error: function(e){ 86 $("#result-div").text("系统错误!"); 87 }, 88 }) 89 }); 90 $("#getcommonuser-btn").on("click",function(){ 91 var userId = $("#userid-input").val(); 92 $.ajax({ 93 url: "/user/getCommonUser", 94 data: { 95 userId: userId 96 }, 97 dataType: "json", 98 success: function(data){ 99 $("#result-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]"); 100 }, 101 error: function(e){ 102 $("#result-div").text("系统错误!"); 103 }, 104 }) 105 }); 106 }); 107</script> 108</html>
3.其他
a.复合缓存(@Caching)与 全局缓存配置(@CacheConfig):
1@RestController 2@RequestMapping("/user2") 3@CacheConfig(cacheNames = "userCache") //全局缓存设置 4public class UserController2 { 5 6 @RequestMapping("/addUser") 7 @Caching( //复合缓存 8 cacheable = { 9 @Cacheable(key="'user2:' + #user.id") 10 }, 11 put = { 12 @CachePut(value = {"common", "common2"}, key="'common2:user2:' + #user.id"), 13 @CachePut(value = {"common3"}, key="'common3:user3:' + #user.id") 14 } 15 ) 16 public User addUser(User user){ 17 int userId = user.getId(); 18 System.out.println("添加缓存"); 19 return new User(userId, "用户名(add)_" + userId, "密码_" + userId); 20 } 21 22}
访问 http://localhost:8080/user2/addUser?id=555 并使用 RedisDesktopManager 查看redis缓存