1. <s id="4jtld"></s>
    1. <span id="4jtld"><meter id="4jtld"></meter></span>

        <span id="4jtld"></span>
      1. <s id="4jtld"><noscript id="4jtld"><i id="4jtld"></i></noscript></s>
        溫馨提示×

        SpringBoot中實現默認緩存的方法

        發布時間:2020-08-15 09:48:36 來源:億速云 閱讀:847 作者:小新 欄目:開發技術

        小編給大家分享一下SpringBoot中實現默認緩存的方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!

        在上一節中,我帶大家學習了在Spring Boot中對緩存的實現方案,尤其是結合Spring Cache的注解的實現方案,接下來在本章節中,我帶大家通過代碼來實現。

        一. Spring Boot實現默認緩存

        1. 創建web項目

        我們按照之前的經驗,創建一個web程序,并將之改造成Spring Boot項目,具體過程略。

        SpringBoot中實現默認緩存的方法

        2. 添加依賴包

        <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
         
        <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
        </dependency>
         
        <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        3. 創建application.yml配置文件

        server:
         port: 8080
        spring:
         application:
         name: cache-demo
         datasource:
         driver-class-name: com.mysql.cj.jdbc.Driver
         username: root
         password: syc
         url: jdbc:mysql://localhost:3306/spring-security&#63;useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&serverTimezone=UTC
         #cache:
         #type: generic #由redis進行緩存,一共有10種緩存方案
         jpa:
         database: mysql
         show-sql: true #開發階段,打印要執行的sql語句.
         hibernate:
          ddl-auto: update

        4. 創建一個緩存配置類

        主要是在該類上添加@EnableCaching注解,開啟緩存功能。

        package com.yyg.boot.config;
         
        import org.springframework.cache.annotation.EnableCaching;
         
        /**
         * @Author 一一哥Sun
         * @Date Created in 2020/4/14
         * @Description Description
         * EnableCaching啟用緩存
         */ 
        @Configuration
        @EnableCaching
        public class CacheConfig {
        }

        5. 創建User實體類

        package com.yyg.boot.domain;
         
        import lombok.Data;
        import lombok.ToString;
         
        import javax.persistence.*;
        import java.io.Serializable;
         
        @Entity
        @Table(name="user")
        @Data
        @ToString
        public class User implements Serializable {
         
         //IllegalArgumentException: DefaultSerializer requires a Serializable payload
         // but received an object of type [com.syc.redis.domain.User]
         
         @Id
         @GeneratedValue(strategy = GenerationType.AUTO)
         private Long id;
         
         @Column
         private String username;
         
         @Column
         private String password;
         
        }

        6. 創建User倉庫類

        package com.yyg.boot.repository;
         
        import com.yyg.boot.domain.User;
        import org.springframework.data.jpa.repository.JpaRepository;
         
        public interface UserRepository extends JpaRepository<User,Long> {
        }

        7. 創建Service服務類

        定義UserService接口

        package com.yyg.boot.service;
         
        import com.yyg.boot.domain.User;
         
        public interface UserService {
         
         User findById(Long id);
         
         User save(User user);
         
         void deleteById(Long id);
         
        }

        實現UserServiceImpl類

        package com.yyg.boot.service.impl;
         
        import com.yyg.boot.domain.User;
        import com.yyg.boot.repository.UserRepository;
        import com.yyg.boot.service.UserService;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.cache.annotation.CacheEvict;
        import org.springframework.cache.annotation.CachePut;
        import org.springframework.cache.annotation.Cacheable;
        import org.springframework.stereotype.Service;
         
        @Service
        public class UserServiceImpl implements UserService {
         
         @Autowired
         private UserRepository userRepository;
         
         //普通的緩存+數據庫查詢代碼實現邏輯:
         //User user=RedisUtil.get(key);
         // if(user==null){
         //  user=userDao.findById(id);
         //  //redis的key="product_item_"+id
         //  RedisUtil.set(key,user);
         // }
         // return user;
         
         /**
          * 注解@Cacheable:查詢的時候才使用該注解!
          * 注意:在Cacheable注解中支持EL表達式
          * redis緩存的key=user_1/2/3....
          * redis的緩存雪崩,緩存穿透,緩存預熱,緩存更新...
          * condition = "#result ne null",條件表達式,當滿足某個條件的時候才進行緩存
          * unless = "#result eq null":當user對象為空的時候,不進行緩存
          */
         @Cacheable(value = "user", key = "#id", unless = "#result eq null")
         @Override
         public User findById(Long id) {
         
          return userRepository.findById(id).orElse(null);
         }
         
         /**
          * 注解@CachePut:一般用在添加和修改方法中
          * 既往數據庫中添加一個新的對象,于此同時也往redis緩存中添加一個對應的緩存.
          * 這樣可以達到緩存預熱的目的.
          */
         @CachePut(value = "user", key = "#result.id", unless = "#result eq null")
         @Override
         public User save(User user) {
          return userRepository.save(user);
         }
         
         /**
          * CacheEvict:一般用在刪除方法中
          */
         @CacheEvict(value = "user", key = "#id")
         @Override
         public void deleteById(Long id) {
          userRepository.deleteById(id);
         }
         
        }

        8. 創建Controller接口方法

        package com.yyg.boot.web;
         
        import com.yyg.boot.domain.User;
        import com.yyg.boot.service.UserService;
        import lombok.extern.slf4j.Slf4j;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.http.HttpStatus;
        import org.springframework.http.ResponseEntity;
        import org.springframework.web.bind.annotation.*;
         
        @RestController
        @RequestMapping("/user")
        @Slf4j
        public class UserController {
         
         @Autowired
         private UserService userService;
         
         @PostMapping
         public User saveUser(@RequestBody User user) {
          return userService.save(user);
         }
         
         @GetMapping("/{id}")
         public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {
          User user = userService.findById(id);
          log.warn("user="+user.hashCode());
          HttpStatus status = user == null &#63; HttpStatus.NOT_FOUND : HttpStatus.OK;
          return new ResponseEntity<>(user, status);
         }
         
         @DeleteMapping("/{id}")
         public String removeUser(@PathVariable("id") Long id) {
          userService.deleteById(id);
          return "ok";
         }
         
        }

        9. 創建入口類

        package com.yyg.boot;
         
        import org.springframework.boot.SpringApplication;
        import org.springframework.boot.autoconfigure.SpringBootApplication;
         
        @SpringBootApplication
        public class CacheApplication {
         
         public static void main(String[] args) {
          SpringApplication.run(CacheApplication.class, args);
         }
         
        }

        10. 完整項目結構

        SpringBoot中實現默認緩存的方法

        11. 啟動項目進行測試

        我們首先調用添加接口,往數據庫中添加一條數據。

        SpringBoot中實現默認緩存的方法

        可以看到數據庫中,已經成功的添加了一條數據。

        SpringBoot中實現默認緩存的方法

        然后測試一下查詢接口方法。

        SpringBoot中實現默認緩存的方法

        此時控制臺打印的User對象的hashCode如下:

        SpringBoot中實現默認緩存的方法

        我們再多次執行查詢接口,發現User對象的hashCode值不變,說明數據都是來自于緩存,而不是每次都重新查詢。

        SpringBoot中實現默認緩存的方法

        至此,我們就實現了Spring Boot中默認的緩存方案。

        看完了這篇文章,相信你對SpringBoot中實現默認緩存的方法有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!

        免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

        主題地圖

        欧美午夜理伦三级在线观看,欧美午夜乱伦片,欧美午夜乱色视频在线观看,欧美午夜免费一区二区,欧美午夜片欧美片在线观看