第三章 springboot + jedisCluster

若是使用的是redis2.x,在項目中使用客戶端分片(Shard)機制。(具體使用方式:第九章 企業項目開發--分佈式緩存Redis(1)  第十章 企業項目開發--分佈式緩存Redis(2)html

若是使用的是redis3.x中的集羣,在項目中使用jedisCluster。java

redis3.2.5集羣搭建:第十二章 redis-cluster搭建(redis-3.2.5)node

一、項目結構web

 

二、pom.xmlredis

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 4 
 5     <modelVersion>4.0.0</modelVersion>
 6 
 7     <groupId>com.xxx</groupId>
 8     <artifactId>myboot</artifactId>
 9     <version>1.0-SNAPSHOT</version>
10 
11     <properties>
12         <java.version>1.8</java.version><!-- 官方推薦 -->
13     </properties>
14     <!-- 引入spring-boot-starter-parent作parent是最好的方式, 
15          可是有時咱們可能要引入咱們本身的parent,此時解決方式有兩種: 
16          1)咱們本身的parent的pom.xml的parent設爲spring-boot-starter-parent(沒有作過驗證,可是感受可行) 
17          2)使用springboot文檔中的方式:見spring-boot-1.2.5-reference.pdf的第13頁 
18     -->
19     <parent> 
20         <groupId>org.springframework.boot</groupId> 
21         <artifactId>spring-boot-starter-parent</artifactId> 
22         <version>1.2.5.RELEASE</version> 
23     </parent>
24 
25     <!-- <dependencyManagement>
26         <dependencies>
27             <dependency>
28                 Import dependency management from Spring Boot
29                 <groupId>org.springframework.boot</groupId>
30                 <artifactId>spring-boot-dependencies</artifactId>
31                 <version>1.2.5.RELEASE</version>
32                 <type>pom</type>
33                 <scope>import</scope>
34             </dependency>
35         </dependencies>
36     </dependencyManagement> -->
37 
38     <!-- 引入實際依賴 -->
39     <dependencies>
40         <dependency>
41             <groupId>org.springframework.boot</groupId>
42             <artifactId>spring-boot-starter-web</artifactId>
43         </dependency>
44         <dependency>
45             <groupId>redis.clients</groupId>
46             <artifactId>jedis</artifactId>
47         </dependency>
48         <dependency>
49             <groupId>com.alibaba</groupId>
50             <artifactId>fastjson</artifactId>
51             <version>1.1.15</version>
52         </dependency>
53         <dependency>
54             <groupId>org.apache.commons</groupId>
55             <artifactId>commons-lang3</artifactId>
56             <version>3.3.2</version>
57         </dependency>
58     </dependencies>
59 
60     <build>
61         <plugins>
62             <!-- 用於將應用打成可直接運行的jar(該jar就是用於生產環境中的jar) 值得注意的是,若是沒有引用spring-boot-starter-parent作parent, 
63                 且採用了上述的第二種方式,這裏也要作出相應的改動 -->
64             <plugin>
65                 <groupId>org.springframework.boot</groupId>
66                 <artifactId>spring-boot-maven-plugin</artifactId>
67             </plugin>
68         </plugins>
69     </build>
70 </project>
View Code

說明:相對於上一章的代碼僅僅引入了jedis的依賴jar。spring

 

三、application.propertiesapache

 1 #user info
 2 user.id=1
 3 user.username=zhaojigang
 4 user.password=123
 5 
 6 #redis cluster
 7 redis.cache.clusterNodes=localhost:8080
 8 redis.cache.commandTimeout=5
 9 #unit:second
10 redis.cache.expireSeconds=120
View Code

說明:相對於上一章的代碼僅僅引入了redis cluster的配置信息json

 

四、Application.java(springboot啓動類,與上一章同樣)數組

五、RedisProperties.java(Redis屬性裝配)瀏覽器

 1 package com.xxx.firstboot.redis;
 2 
 3 import org.springframework.boot.context.properties.ConfigurationProperties;
 4 import org.springframework.stereotype.Component;
 5 
 6 @Component
 7 @ConfigurationProperties(prefix = "redis.cache")
 8 public class RedisProperties {
 9 
10     private int    expireSeconds;
11     private String clusterNodes;
12     private int    commandTimeout;
13 
14     public int getExpireSeconds() {
15         return expireSeconds;
16     }
17 
18     public void setExpireSeconds(int expireSeconds) {
19         this.expireSeconds = expireSeconds;
20     }
21 
22     public String getClusterNodes() {
23         return clusterNodes;
24     }
25 
26     public void setClusterNodes(String clusterNodes) {
27         this.clusterNodes = clusterNodes;
28     }
29 
30     public int getCommandTimeout() {
31         return commandTimeout;
32     }
33 
34     public void setCommandTimeout(int commandTimeout) {
35         this.commandTimeout = commandTimeout;
36     }
37 
38 }
View Code

說明:與上一章的User相似,採用@ConfigurationProperties註解自動讀取application.properties文件的內容並裝配到RedisProperties的每個屬性中去。

 

六、JedisClusterConfig.java(獲取JedisCluster單例)

 1 package com.xxx.firstboot.redis;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.context.annotation.Bean;
 8 import org.springframework.context.annotation.Configuration;
 9 
10 import redis.clients.jedis.HostAndPort;
11 import redis.clients.jedis.JedisCluster;
12 
13 @Configuration
14 public class JedisClusterConfig {
15 
16     @Autowired
17     private RedisProperties redisProperties;
18 
19     /**
20      * 注意:
21      * 這裏返回的JedisCluster是單例的,而且能夠直接注入到其餘類中去使用
22      * @return
23      */
24     @Bean
25     public JedisCluster getJedisCluster() {
26         String[] serverArray = redisProperties.getClusterNodes().split(",");//獲取服務器數組(這裏要相信本身的輸入,因此沒有考慮空指針問題)
27         Set<HostAndPort> nodes = new HashSet<>();
28 
29         for (String ipPort : serverArray) {
30             String[] ipPortPair = ipPort.split(":");
31             nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
32         }
33 
34         return new JedisCluster(nodes, redisProperties.getCommandTimeout());
35     }
36 
37 }
View Code

說明:

  • 該類注入了RedisProperties類,能夠直接讀取其屬性
  • 這裏沒有對jedis連接池提供更多的配置(jedis-2.5.x好像不支持,jedis-2.6.x支持),具體的配置屬性能夠查看文章開頭第一篇博客

注意:

  • 該類使用了Java註解,@Configuration與@Bean,
    • 在方法上使用@Bean註解可讓方法的返回值爲單例,
    • 該方法的返回值能夠直接注入到其餘類中去使用
    • @Bean註解是方法級別的
  • 若是使用的是經常使用的spring註解@Component,
    • 在方法上沒有註解的話,方法的返回值就會是一個多例,
    • 該方法的返回值不能夠直接注入到其餘類去使用
    • 該方式的註解是類級別的

 

七、MyRedisTemplate.java(具體redis操做)

 1 package com.xxx.firstboot.redis;
 2 
 3 import org.slf4j.Logger;
 4 import org.slf4j.LoggerFactory;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Component;
 7 
 8 import redis.clients.jedis.JedisCluster;
 9 
10 @Component
11 public class MyRedisTemplate {
12     private static final Logger LOGGER    = LoggerFactory.getLogger(MyRedisTemplate.class);
13 
14     @Autowired
15     private JedisCluster        jedisCluster;
16 
17     @Autowired
18     private RedisProperties     redisProperties;
19 
20     private static final String KEY_SPLIT = ":"; //用於隔開緩存前綴與緩存鍵值 
21 
22     /**
23      * 設置緩存 
24      * @param prefix 緩存前綴(用於區分緩存,防止緩存鍵值重複)
25      * @param key    緩存key
26      * @param value  緩存value
27      */
28     public void set(String prefix, String key, String value) {
29         jedisCluster.set(prefix + KEY_SPLIT + key, value);
30         LOGGER.debug("RedisUtil:set cache key={},value={}", prefix + KEY_SPLIT + key, value);
31     }
32 
33     /**
34      * 設置緩存,而且本身指定過時時間
35      * @param prefix
36      * @param key
37      * @param value
38      * @param expireTime 過時時間
39      */
40     public void setWithExpireTime(String prefix, String key, String value, int expireTime) {
41         jedisCluster.setex(prefix + KEY_SPLIT + key, expireTime, value);
42         LOGGER.debug("RedisUtil:setWithExpireTime cache key={},value={},expireTime={}", prefix + KEY_SPLIT + key, value,
43             expireTime);
44     }
45 
46     /**
47      * 設置緩存,而且由配置文件指定過時時間
48      * @param prefix
49      * @param key
50      * @param value
51      */
52     public void setWithExpireTime(String prefix, String key, String value) {
53         int EXPIRE_SECONDS = redisProperties.getExpireSeconds();
54         jedisCluster.setex(prefix + KEY_SPLIT + key, EXPIRE_SECONDS, value);
55         LOGGER.debug("RedisUtil:setWithExpireTime cache key={},value={},expireTime={}", prefix + KEY_SPLIT + key, value,
56             EXPIRE_SECONDS);
57     }
58 
59     /**
60      * 獲取指定key的緩存
61      * @param prefix
62      * @param key
63      */
64     public String get(String prefix, String key) {
65         String value = jedisCluster.get(prefix + KEY_SPLIT + key);
66         LOGGER.debug("RedisUtil:get cache key={},value={}", prefix + KEY_SPLIT + key, value);
67         return value;
68     }
69 
70     /**
71      * 刪除指定key的緩存
72      * @param prefix
73      * @param key
74      */
75     public void deleteWithPrefix(String prefix, String key) {
76         jedisCluster.del(prefix + KEY_SPLIT + key);
77         LOGGER.debug("RedisUtil:delete cache key={}", prefix + KEY_SPLIT + key);
78     }
79     
80     public void delete(String key) {
81         jedisCluster.del(key);
82         LOGGER.debug("RedisUtil:delete cache key={}", key);
83     }
84 
85 }
View Code

注意:

這裏只是使用了jedisCluster作了一些字符串的操做,對於list/set/sorted set/hash的操做,能夠參考開頭的兩篇博客。

 

八、MyConstants.java(緩存前綴常量定義類)

1 package com.xxx.firstboot.common;
2 
3 /**
4  * 定義一些常量
5  */
6 public class MyConstants {
7     public static final String USER_FORWARD_CACHE_PREFIX = "myboot:user";// user緩存前綴
8 }
View Code

注意:

  • 根據業務特色定義redis的緩存前綴,有助於防止緩存重複致使的緩存覆蓋問題
  • 緩存前綴使用":"作分隔符,這是推薦作法(這個作法能夠在使用redis-desktop-manager的過程看出來)

 

九、UserController.java(測試)

 

 1 package com.xxx.firstboot.web;
 2 
 3 import org.apache.commons.lang3.StringUtils;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 import org.springframework.web.bind.annotation.RequestParam;
 7 import org.springframework.web.bind.annotation.RestController;
 8 
 9 import com.alibaba.fastjson.JSON;
10 import com.xxx.firstboot.common.MyConstants;
11 import com.xxx.firstboot.domain.User;
12 import com.xxx.firstboot.redis.MyRedisTemplate;
13 import com.xxx.firstboot.service.UserService;
14 
15 /**
16  * @RestController:spring mvc的註解,
17  * 至關於@Controller與@ResponseBody的合體,能夠直接返回json
18  */
19 @RestController
20 @RequestMapping("/user")
21 public class UserController {
22 
23     @Autowired
24     private UserService userService;
25     
26     @Autowired
27     private MyRedisTemplate myRedisTemplate;
28 
29     @RequestMapping("/getUser")
30     public User getUser() {
31         return userService.getUser();
32     }
33     
34     @RequestMapping("/testJedisCluster")
35     public User testJedisCluster(@RequestParam("username") String username){
36         String value =  myRedisTemplate.get(MyConstants.USER_FORWARD_CACHE_PREFIX, username);
37         if(StringUtils.isBlank(value)){
38             myRedisTemplate.set(MyConstants.USER_FORWARD_CACHE_PREFIX, username, JSON.toJSONString(getUser()));
39             return null;
40         }
41         return JSON.parseObject(value, User.class);
42     }
43 
44 }
View Code

 

說明:相對於上一章,只是添加了測試緩存的方法testJedisCluster。

 

測試:

在Application.properties右擊-->run as-->java application,在瀏覽器輸入"localhost:8080/user/testJedisCluster?username=xxx"便可。

 

附:對於redis的測試,咱們有時須要查看執行set後,緩存是否存入redis的db中了,有兩種方式

  • 執行set後,get數據,以後修改數據,在get數據,比較兩次get的數據是否相同便可
  • 有時,這些數據是沒法修改的(假設該數據是咱們從第三方接口得來的),這個時候能夠使用redis-desktop-manager這個軟件來查看緩存是否存入redis(該軟件的使用比較簡單,查看官網)
相關文章
相關標籤/搜索