1. 程式人生 > 程式設計 >Spring Boot整合Spring Cache及Redis過程解析

Spring Boot整合Spring Cache及Redis過程解析

這篇文章主要介紹了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>
  <h1>測試</h1>
  <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
        },})
    });
    $("#deleteuser-btn").on("click",function(){
      var userId = $("#userid-input").val();
      $.ajax({
        url: "/user/deleteUser",success: function(data){
          $("#result-div").text(data);
        },})
    });
    $("#getcommonuser-btn").on("click",function(){
      var userId = $("#userid-input").val();
      $.ajax({
        url: "/user/getCommonUser",})
    });
  });
</script>
</html>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。