1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        Spring Boot 集成 Redis 實(shí)現(xiàn)數(shù)據(jù)緩存

        共 11689字,需瀏覽 24分鐘

         ·

        2020-08-06 14:32







        Spring Boot 集成 Redis 實(shí)現(xiàn)數(shù)據(jù)緩存,只要添加一些注解方法,就可以動態(tài)的去操作緩存了,減少代碼的操作。

        在這個例子中我使用的是 Redis,其實(shí)緩存類型還有很多,例如 Ecache、Mamercache、Caffeine  等。

        Redis 簡介

        Redis 是一個開源,高級的鍵值存儲和一個適用的解決方案,用于構(gòu)建高性能,可擴(kuò)展的 Web 應(yīng)用程序。

        Redis 相關(guān)的知識就不在這里贅述了,感興趣的可以公眾號回復(fù) Redis 看下 Redis 系列文章。

        下面我們在 Spring Boot 中集成 Redis 來實(shí)現(xiàn)數(shù)據(jù)緩存。

        Spring Boot 集成 Redis 實(shí)現(xiàn)緩存

        Spring Boot 集成 Redis 實(shí)現(xiàn)緩存主要分為以下三步:

        1. 加入 Redis 依賴
        2. 加入 Redis 配置
        3. 演示 Redis 緩存

        加入依賴

        首先創(chuàng)建一個項目,在項目中加入 Redis 依賴,項目依賴如下所示(由于使用 Redis 連接池,需額外引入 commons-pool2):

        
              
               
             org.springframework.boot
             spring-boot-starter-web


             org.springframework.boot
             spring-boot-starter-data-redis


             org.apache.commons
             commons-pool2

        spring-boot-starter-data-redis 1.X 版本默認(rèn)使用 Jedis 客戶端,在 2.X 版本默認(rèn)開始使用 Lettuce 客戶端,如果習(xí)慣使用 Jedis 的話,可以從 spring-boot-starter-data-redis 中排除 Lettuce 并引入 Jedis。

        加入配置

        在配置文件 application.properties 中配置 Redis 的相關(guān)參數(shù),具體內(nèi)容如下:

        #Redis 索引(0~15,默認(rèn)為 0)
        spring.redis.database=0
        spring.redis.host=127.0.0.1
        #Redis 密碼,如果沒有就默認(rèn)不配置此參數(shù)
        spring.redis.password=
        spring.redis.port=6379
        #Redis 連接的超時時間
        spring.redis.timeout=1000
        #連接池最大連接數(shù)(使用負(fù)值表示沒有限制)
        spring.redis.lettuce.pool.max-active=20
        #連接池最大阻塞等待時間(使用負(fù)值表示沒有限制)
        spring.redis.lettuce.pool.max-wait=-1
        #連接池中的最大空閑連接
        spring.redis.lettuce.pool.max-idle=10
        #連接池中的最小空閑連接
        spring.redis.lettuce.pool.min-idle=0

        接下來在 config 包下創(chuàng)建一個 Redis 配置類 RedisConfig,在配置類上加入注解 @Configuration,注入一個 CacheManager 來配置一些相關(guān)信息,代碼如下:

        @Configuration
        public class RedisConfig {

            @Bean
            public CacheManager cacheManager(RedisConnectionFactory factory) {
                RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                        .entryTtl(Duration.ofMinutes(30))
                        .prefixKeysWith("cache:user:")
                        .disableCachingNullValues()
                        .serializeKeysWith(keySerializationPair())
                        .serializeValuesWith(valueSerializationPair());
                return RedisCacheManager.builder(factory)
                        .withCacheConfiguration("user", redisCacheConfiguration).build();
            }

            private RedisSerializationContext.SerializationPair   keySerializationPair ()  {
                return RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer());
            }

            private RedisSerializationContext.SerializationPair valueSerializationPair() {
                return RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer());
            }
        }

        首先通過 RedisCacheConfiguration 生成默認(rèn)配置,然后對緩存進(jìn)行自定義化配置,比如過期時間、緩存前綴、key/value 序列化方法等,然后構(gòu)建出一個 RedisCacheManager,其中通過 keySerializationPair 方法為 key 配置序列化,valueSerializationPair 為 value 配置序列化。

        定義用戶實(shí)體類

        domain 包下創(chuàng)建一個用戶實(shí)體類:

        public class User {

            private Long id;

            private String name;

            private String password;
            // 省略 getter/setter
        }

        在服務(wù)中使用 SpringCache 注解

        service 包下定義用戶接口,分別包含添加用戶、查詢用戶、更新用戶以及刪除用戶四個接口,具體代碼如下:

        public interface UserService {

            void addUser(User user);

            User getUserById(Long id);

            User updateUser(User user);

            void deleteById(Long id);
        }

        然后編寫實(shí)現(xiàn)類,為了方便演示,在這里使用 Map userMap ,沒有去連接數(shù)據(jù)庫,其中用到的注解有 @CacheConfig、@Cacheable、@CachePut 以及 @CacheEvict,具體代碼如下:

        @Service
        @CacheConfig(cacheNames = "user")
        public class UserServiceImpl implements UserService {

            Map  userMap = Collections.synchronizedMap( new HashMap<>());

             @Override
             public void addUser(User user) {
                userMap.put(user.getId(), user);
            }

             @Override
             @Cacheable(key =  "#id")
             public User getUserById(Long id) {
                 if (!userMap.containsKey(id)) {
                     return  null;
                }
                 return userMap.get(id);
            }

             @Override
             @CachePut(key =  "#user.id")
             public User updateUser(User user) {
                 if (!userMap.containsKey(user.getId())) {
                     throw  new RuntimeException( "不存在該用戶");
                }
                User newUser = userMap.get(user.getId());
                newUser.setPassword(user.getPassword());
                userMap.put(newUser.getId(), newUser);
                 return newUser;
            }

             @Override
             @CacheEvict(key =  "#id")
             public void deleteById(Long id) {
                userMap.remove(id);
            }
        }

        在這里說下這幾個注解:

        @CacheConfig 類級別的緩存注解,允許共享緩存名稱

        @Cacheable 觸發(fā)緩存入口

        一般用于查詢操作,根據(jù) key 查詢緩存.

        1. 如果 key 不存在,查詢 db,并將結(jié)果更新到緩存中。
        2. 如果 key 存在,直接查詢緩存中的數(shù)據(jù)。

        @CacheEvict 觸發(fā)移除緩存

        根據(jù) key 刪除緩存中的數(shù)據(jù)。

        @CacahePut 更新緩存

        一般用于更新和插入操作,每次都會請求 db,通過 key 去 Redis 中進(jìn)行操作。

        1. 如果 key 存在,更新內(nèi)容
        2. 如果 key 不存在,插入內(nèi)容。

        最后,在 controller 包下創(chuàng)建一個 UserController 類,提供用戶 API 接口(未使用數(shù)據(jù)庫),代碼如下:

        @RestController
        @RequestMapping("/user")
        public class UserController {

            @Autowired
            private UserService userService;

            @GetMapping("/{id}")
            public ResponseEntity   getUser (@PathVariable Long id)  {
                return ResponseEntity.status(HttpStatus.CREATED).body(userService.getUserById(id));
            }

            @PostMapping
            public ResponseEntity   createUser (@RequestBody User user)  {
                userService.addUser(user);
                return ResponseEntity.status(HttpStatus.CREATED).body("SUCCESS");
            }

            @PutMapping
            public ResponseEntity   updateUser (@RequestBody User user)  {
                return ResponseEntity.status(HttpStatus.CREATED).body(userService.updateUser(user));
            }

            @DeleteMapping("/{id}")
            public ResponseEntity   deleteUser (@PathVariable Long id)  {
                userService.deleteById(id);
                return ResponseEntity.status(HttpStatus.CREATED).body("SUCCESS");
            }
        }

        啟動類添加開啟緩存注解

        @SpringBootApplication
        @EnableCaching
        public class RedisCacheApplication {

            public static void main(String[] args) {
                SpringApplication.run(RedisCacheApplication.class, args);
            }
        }

        @EnableCaching 表明開啟緩存,Spring Boot 會自動配置 Redis 緩存的 CacheManager。

        啟動項目,先調(diào)用添加用戶接口,添加用戶 wupx,id 為 1,在 getUserById 方法打斷點(diǎn),第一次調(diào)用 getUser 接口獲取用戶的時候,會運(yùn)行到斷點(diǎn)處,第二次調(diào)用 getUser 不會運(yùn)行到斷點(diǎn)處,而是直接從 Redis 中讀取緩存數(shù)據(jù)。

        通過 Redis 可視化工具 RedisDesktopManager 查看,結(jié)果如圖所示:

        到此為止,我們就完成了 Spring Boot 與 Redis 的集成實(shí)現(xiàn)數(shù)據(jù)緩存。

        總結(jié)

        Spring Boot 集成 Redis 實(shí)現(xiàn)數(shù)據(jù)緩存還是比較輕松的,Spring 提供了緩存注解,使用這些注解可以有效簡化編程過程,大家可以自己動手實(shí)踐下。

        本文的完整代碼在 https://github.com/wupeixuan/SpringBoot-Learn 的 redis-cache 目錄下。

        留言討論

        最好的關(guān)系就是互相成就,大家的點(diǎn)贊、在看、分享、留言四連就是我創(chuàng)作的最大動力。


        參考

        https://github.com/wupeixuan/SpringBoot-Learn


               
           
        Spring Boot 集成阿里云 OSS 進(jìn)行文件存儲
        Spring Boot 集成 Elasticsearch 實(shí)戰(zhàn)
        Spring Boot 集成 WebSocket 實(shí)現(xiàn)服務(wù)端推送消息到客戶端

        瀏覽 50
        點(diǎn)贊
        評論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點(diǎn)贊
        評論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            麻豆国产在线 | 91人妻无码一区二区三区 | 69国产精品成人无码 | 人人爽久久涩噜噜噜小说 | 高清freesexmovies性tv出水 | 日韩成人一区二区三区影院 | 淫色淫色 www.b2gd.com | 欧美毛片少妇 蜜挑 | 国产乱伦免费看 | 亚 洲 成 人 视 频 在 线 |