溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

如何解析SpringBoot整合SpringCache及Redis過(guò)程

發(fā)布時(shí)間:2021-10-13 15:55:41 來(lái)源:億速云 閱讀:117 作者:柒染 欄目:編程語(yǔ)言

這篇文章將為大家詳細(xì)講解有關(guān)如何解析SpringBoot整合SpringCache及Redis過(guò)程,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

1.安裝redis

a.由于官方是沒(méi)有Windows版的,所以我們需要下載微軟開(kāi)發(fā)的redis,網(wǎng)址:

https://github.com/MicrosoftArchive/redis/releases

b.解壓后,在redis根目錄打開(kāi)cmd界面,輸入:redis-server.exe redis.windows.conf,啟動(dòng)redis(關(guān)閉cmd窗口即停止)

2.使用

a.創(chuàng)建SpringBoot工程,選擇maven依賴(lài)

<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: 8080spring: # redis相關(guān)配置 redis:  database: 0  host: localhost  port: 6379  password:  jedis:   pool:    # 連接池最大連接數(shù)(使用負(fù)值表示沒(méi)有限制)    max-active: 8    # 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒(méi)有限制)    max-wait: -1ms    # 連接池中的最大空閑連接    max-idle: 5    # 連接池中的最小空閑連接    min-idle: 0    # 連接超時(shí)時(shí)間(毫秒)默認(rèn)是2000ms  timeout: 2000ms # thymeleaf熱更新 thymeleaf:  cache: false

c.創(chuàng)建RedisConfig配置類(lèi)

@Configuration@EnableCaching //開(kāi)啟緩存public class RedisConfig {  /**   * 緩存管理器   * @param redisConnectionFactory   * @return   */  @Bean  public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {    // 生成一個(gè)默認(rèn)配置,通過(guò)config對(duì)象即可對(duì)緩存進(jìn)行自定義配置    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();    // 設(shè)置緩存的默認(rèn)過(guò)期時(shí)間,也是使用Duration設(shè)置    config = config.entryTtl(Duration.ofMinutes(30))        // 設(shè)置 key為string序列化        .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))        // 設(shè)置value為json序列化        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))        // 不緩存空值        .disableCachingNullValues();    // 對(duì)每個(gè)緩存空間應(yīng)用不同的配置    Map<String, RedisCacheConfiguration> configMap = new HashMap<>();    configMap.put("userCache", config.entryTtl(Duration.ofSeconds(60)));    // 使用自定義的緩存配置初始化一個(gè)cacheManager    RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)        //默認(rèn)配置        .cacheDefaults(config)        // 特殊配置(一定要先調(diào)用該方法設(shè)置初始化的緩存名,再初始化相關(guān)的配置)        .initialCacheNames(configMap.keySet())        .withInitialCacheConfigurations(configMap)        .build();    return cacheManager;  }  /**   * Redis模板類(lèi)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來(lái)序列化和反序列化redis的value值    Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);    //json轉(zhuǎn)對(duì)象類(lèi),不設(shè)置默認(rèn)的會(huì)將json轉(zhuǎn)成hashmap    ObjectMapper mapper = new ObjectMapper();    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);    serializer.setObjectMapper(mapper);    return serializer;  }}

d.創(chuàng)建entity實(shí)體類(lèi)

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.創(chuàng)建Service

@Servicepublic class UserService {  //查詢(xún):先查緩存是是否有,有則直接取緩存中數(shù)據(jù),沒(méi)有則運(yùn)行方法中的代碼并緩存  @Cacheable(value = "userCache", key = "'user:' + #userId")  public User getUser(int userId) {    System.out.println("執(zhí)行此方法,說(shuō)明沒(méi)有緩存");    return new User(userId, "用戶(hù)名(get)_" + userId, "密碼_" + userId);  }  //添加:運(yùn)行方法中的代碼并緩存  @CachePut(value = "userCache", key = "'user:' + #user.id")  public User addUser(User user){    int userId = user.getId();    System.out.println("添加緩存");    return new User(userId, "用戶(hù)名(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("執(zhí)行此方法,說(shuō)明沒(méi)有緩存(測(cè)試公共配置是否生效)");    return new User(userId, "用戶(hù)名(common)_" + userId, "密碼_" + userId);  }}

f.創(chuàng)建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);  }}

@Controllerpublic class HomeController {  //默認(rèn)頁(yè)面  @RequestMapping("/")  public String login() {    return "test";  }}

g.在 templates 目錄下,寫(xiě)書(shū) test.html 頁(yè)面

<!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><p>  <h2>測(cè)試</h2>  <p class="row">    <label>用戶(hù)ID:</label><input id="userid-input" type="text" name="userid"/>  </p>  <p class="row">    <p class="col">      <button id="getuser-btn">獲取用戶(hù)</button>    </p>    <p class="col">      <button id="adduser-btn">添加用戶(hù)</button>    </p>    <p class="col">      <button id="deleteuser-btn">刪除用戶(hù)</button>    </p>    <p class="col">      <button id="getcommonuser-btn">獲取用戶(hù)(common)</button>    </p>  </p>  <p class="row" id="result-p"></p></p></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-p").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]");        },        error: function(e){          $("#result-p").text("系統(tǒng)錯(cuò)誤!");        },      })    });    $("#adduser-btn").on("click",function(){      var userId = $("#userid-input").val();      $.ajax({        url: "/user/addUser",        data: {          id: userId        },        dataType: "json",        success: function(data){          $("#result-p").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]");        },        error: function(e){          $("#result-p").text("系統(tǒng)錯(cuò)誤!");        },      })    });    $("#deleteuser-btn").on("click",function(){      var userId = $("#userid-input").val();      $.ajax({        url: "/user/deleteUser",        data: {          userId: userId        },        dataType: "json",        success: function(data){          $("#result-p").text(data);        },        error: function(e){          $("#result-p").text("系統(tǒng)錯(cuò)誤!");        },      })    });    $("#getcommonuser-btn").on("click",function(){      var userId = $("#userid-input").val();      $.ajax({        url: "/user/getCommonUser",        data: {          userId: userId        },        dataType: "json",        success: function(data){          $("#result-p").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]");        },        error: function(e){          $("#result-p").text("系統(tǒng)錯(cuò)誤!");        },      })    });  });</script></html>

關(guān)于如何解析SpringBoot整合SpringCache及Redis過(guò)程就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI