您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關Spring Boot整合Spring Cache及Redis過程的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
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依賴
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ..... </dependencies>
b.配置 application.yml 配置文件
server: port: 8080 spring: # redis相關配置 redis: database: 0 host: localhost port: 6379 password: jedis: pool: # 連接池最大連接數(使用負值表示沒有限制) max-active: 8 # 連接池最大阻塞等待時間(使用負值表示沒有限制) max-wait: -1ms # 連接池中的最大空閑連接 max-idle: 5 # 連接池中的最小空閑連接 min-idle: 0 # 連接超時時間(毫秒)默認是2000ms timeout: 2000ms # thymeleaf熱更新 thymeleaf: cache: false
c.創建RedisConfig配置類
@Configuration @EnableCaching //開啟緩存 public class RedisConfig { /** * 緩存管理器 * @param redisConnectionFactory * @return */ @Bean public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { // 生成一個默認配置,通過config對象即可對緩存進行自定義配置 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); // 設置緩存的默認過期時間,也是使用Duration設置 config = config.entryTtl(Duration.ofMinutes(30)) // 設置 key為string序列化 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // 設置value為json序列化 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer())) // 不緩存空值 .disableCachingNullValues(); // 對每個緩存空間應用不同的配置 Map<String, RedisCacheConfiguration> configMap = new HashMap<>(); configMap.put("userCache", config.entryTtl(Duration.ofSeconds(60))); // 使用自定義的緩存配置初始化一個cacheManager RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory) //默認配置 .cacheDefaults(config) // 特殊配置(一定要先調用該方法設置初始化的緩存名,再初始化相關的配置) .initialCacheNames(configMap.keySet()) .withInitialCacheConfigurations(configMap) .build(); return cacheManager; } /** * Redis模板類redisTemplate * @param factory * @return */ @Bean public RedisTemplate redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); // key采用String的序列化方式 template.setKeySerializer(new StringRedisSerializer()); // hash的key也采用String的序列化方式 template.setHashKeySerializer(new StringRedisSerializer()); // value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer()); // hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer()); return template; } /** * json序列化 * @return */ private RedisSerializer<Object> jackson2JsonRedisSerializer() { //使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值 Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class); //json轉對象類,不設置默認的會將json轉成hashmap ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper(mapper); return serializer; } }
d.創建entity實體類
public class User implements Serializable { private int id; private String userName; private String userPwd; public User(){} public User(int id, String userName, String userPwd) { this.id = id; this.userName = userName; this.userPwd = userPwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } }
e.創建Service
@Service public class UserService { //查詢:先查緩存是是否有,有則直接取緩存中數據,沒有則運行方法中的代碼并緩存 @Cacheable(value = "userCache", key = "'user:' + #userId") public User getUser(int userId) { System.out.println("執行此方法,說明沒有緩存"); return new User(userId, "用戶名(get)_" + userId, "密碼_" + userId); } //添加:運行方法中的代碼并緩存 @CachePut(value = "userCache", key = "'user:' + #user.id") public User addUser(User user){ int userId = user.getId(); System.out.println("添加緩存"); return new User(userId, "用戶名(add)_" + userId, "密碼_" + userId); } //刪除:刪除緩存 @CacheEvict(value = "userCache", key = "'user:' + #userId") public boolean deleteUser(int userId){ System.out.println("刪除緩存"); return true; } @Cacheable(value = "common", key = "'common:user:' + #userId") public User getCommonUser(int userId) { System.out.println("執行此方法,說明沒有緩存(測試公共配置是否生效)"); return new User(userId, "用戶名(common)_" + userId, "密碼_" + userId); } }
f.創建Controller
@RestController @RequestMapping("/user") public class UserController { @Resource private UserService userService; @RequestMapping("/getUser") public User getUser(int userId) { return userService.getUser(userId); } @RequestMapping("/addUser") public User addUser(User user){ return userService.addUser(user); } @RequestMapping("/deleteUser") public boolean deleteUser(int userId){ return userService.deleteUser(userId); } @RequestMapping("/getCommonUser") public User getCommonUser(int userId) { return userService.getCommonUser(userId); } }
@Controller public class HomeController { //默認頁面 @RequestMapping("/") public String login() { return "test"; } }
g.在 templates 目錄下,寫書 test.html 頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> <style type="text/css"> .row{ margin:10px 0px; } .col{ display: inline-block; margin:0px 5px; } </style> </head> <body> <div> <h2>測試</h2> <div class="row"> <label>用戶ID:</label><input id="userid-input" type="text" name="userid"/> </div> <div class="row"> <div class="col"> <button id="getuser-btn">獲取用戶</button> </div> <div class="col"> <button id="adduser-btn">添加用戶</button> </div> <div class="col"> <button id="deleteuser-btn">刪除用戶</button> </div> <div class="col"> <button id="getcommonuser-btn">獲取用戶(common)</button> </div> </div> <div class="row" id="result-div"></div> </div> </body> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> $(function() { $("#getuser-btn").on("click",function(){ var userId = $("#userid-input").val(); $.ajax({ url: "/user/getUser", data: { userId: userId }, dataType: "json", success: function(data){ $("#result-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]"); }, error: function(e){ $("#result-div").text("系統錯誤!"); }, }) }); $("#adduser-btn").on("click",function(){ var userId = $("#userid-input").val(); $.ajax({ url: "/user/addUser", data: { id: userId }, dataType: "json", success: function(data){ $("#result-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]"); }, error: function(e){ $("#result-div").text("系統錯誤!"); }, }) }); $("#deleteuser-btn").on("click",function(){ var userId = $("#userid-input").val(); $.ajax({ url: "/user/deleteUser", data: { userId: userId }, dataType: "json", success: function(data){ $("#result-div").text(data); }, error: function(e){ $("#result-div").text("系統錯誤!"); }, }) }); $("#getcommonuser-btn").on("click",function(){ var userId = $("#userid-input").val(); $.ajax({ url: "/user/getCommonUser", data: { userId: userId }, dataType: "json", success: function(data){ $("#result-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]"); }, error: function(e){ $("#result-div").text("系統錯誤!"); }, }) }); }); </script> </html>
關于“Spring Boot整合Spring Cache及Redis過程的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。