亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring Boot整合Spring Cache及Redis過(guò)程解析

 更新時(shí)間:2019年12月10日 16:54:27   作者:晨M風(fēng)  
這篇文章主要介紹了Spring Boot整合Spring Cache及Redis過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

這篇文章主要介紹了Spring Boot整合Spring Cache及Redis過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

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依賴

<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相關(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配置類

@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模板類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ì)象類,不設(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í)體類

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

@Service
public class UserService {

  //查詢:先查緩存是是否有,有則直接取緩存中數(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, "用戶名(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, "用戶名(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, "用戶名(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);
  }

}
@Controller
public 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>
<div>
  <h1>測(cè)試</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("系統(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-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]");
        },
        error: function(e){
          $("#result-div").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-div").text(data);
        },
        error: function(e){
          $("#result-div").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-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]");
        },
        error: function(e){
          $("#result-div").text("系統(tǒng)錯(cuò)誤!");
        },
      })
    });
  });
</script>
</html>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java通過(guò)URL獲取公眾號(hào)文章生成HTML的方法

    Java通過(guò)URL獲取公眾號(hào)文章生成HTML的方法

    這篇文章主要介紹了Java通過(guò)URL獲取公眾號(hào)文章生成HTML的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • 圖解JAVA中Spring Aop作用

    圖解JAVA中Spring Aop作用

    這篇文章主要介紹了Java的Spring框架下的AOP的作用,需要的朋友可以參考
    2017-04-04
  • Windows下將JAVA?jar注冊(cè)成windows服務(wù)的方法

    Windows下將JAVA?jar注冊(cè)成windows服務(wù)的方法

    這篇文章主要介紹了Windows下將JAVA?jar注冊(cè)成windows服務(wù)的方法,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-07-07
  • java 使用Graphics2D在圖片上寫(xiě)字

    java 使用Graphics2D在圖片上寫(xiě)字

    這篇文章主要介紹了java 使用Graphics2D在圖片上寫(xiě)字,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • Java 生成二維碼的工具資料整理

    Java 生成二維碼的工具資料整理

    本文主要介紹Java 生成二維碼的幾種方法,這里給大家詳細(xì)介紹了java生成二維碼的三種工具,并附有示例代碼供大家參考,開(kāi)發(fā)java 二維碼的朋友可以參考下
    2016-08-08
  • IntelliJ IDEA 2021.1 EAP 4 發(fā)布:字體粗細(xì)可調(diào)整Git commit template 支持

    IntelliJ IDEA 2021.1 EAP 4 發(fā)布:字體粗細(xì)可調(diào)整Git commit template 支持

    這篇文章主要介紹了IntelliJ IDEA 2021.1 EAP 4 發(fā)布:字體粗細(xì)可調(diào)整,Git commit template 支持,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-02-02
  • java快速生成數(shù)據(jù)庫(kù)文檔詳情

    java快速生成數(shù)據(jù)庫(kù)文檔詳情

    這篇文章主要介紹了java快速生成數(shù)據(jù)庫(kù)文檔詳情,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下
    2022-07-07
  • Java多線程 ReentrantLock互斥鎖詳解

    Java多線程 ReentrantLock互斥鎖詳解

    這篇文章主要介紹了Java多線程 ReentrantLock互斥鎖詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • SpringBoot實(shí)現(xiàn)模塊日志入庫(kù)的項(xiàng)目實(shí)踐

    SpringBoot實(shí)現(xiàn)模塊日志入庫(kù)的項(xiàng)目實(shí)踐

    本文主要介紹了SpringBoot實(shí)現(xiàn)模塊日志入庫(kù)的項(xiàng)目實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • mybatis的if判斷integer問(wèn)題

    mybatis的if判斷integer問(wèn)題

    這篇文章主要介紹了mybatis的if判斷integer問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03

最新評(píng)論