由淺入深學習springboot中使用redis,springbootredis
很多時候,我們會在springboot中配置redis,但是就那麼幾個配置就配好了,沒辦法知道為什麼,這裡就詳細的講解一下
這裡假設已經成功建立了一個springboot項目。
redis串連工廠類
第一步,需要加上springboot的redis jar包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency>
然後我們寫一個配置類,建立了一個redis串連的工廠的spring bean。(Redis串連工廠會產生到Redis資料庫伺服器的串連)
@Configurationpublic class RedisConfig { @Bean public RedisConnectionFactory redisCF(){ //如果什麼參數都不設定,預設串連本地6379連接埠 JedisConnectionFactory factory = new JedisConnectionFactory(); factory.setPort(6379); factory.setHostName("localhost"); return factory; }}
單元測試,看看這個Factory 方法的使用
@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = Application.class)public class RedisTest { @Autowired RedisConnectionFactory factory; @Test public void testRedis(){ //得到一個串連 RedisConnection conn = factory.getConnection(); conn.set("hello".getBytes(), "world".getBytes()); System.out.println(new String(conn.get("hello".getBytes()))); }}
輸出結果 :world,說明已經成功擷取到串連,並且往redis擷取添加資料,
template(模版)
但是我們發現每次添加的key和value都是byte數群組類型(使用很麻煩),於是spring為我們帶來了redis template(模版)
Spring Data Redis提供了兩個模板:
RedisTemplate
StringRedisTemplate
首先我們先建立一個RedisTemplate模板類,類型的key是String類型,value是Object類型(如果key和value都是String類型,建議使用StringRedisTemplate)
@Bean public RedisTemplate redisTemplate(RedisConnectionFactory factory){ //建立一個模板類 RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); //將剛才的redis串連工廠設定到模板類中 template.setConnectionFactory(factory); return template; }
單元測試
@Autowired RedisTemplate<String, Object> template; @Test public void testRedisTemplate(){ template.opsForValue().set("key1", "value1"); System.out.println(template.opsForValue().get("key1")); }
得到結果輸出value1,是不是很方便了呢。
如果是操作集合呢,也很方便的哈。
@Test public void testRedisTemplateList(){ Pruduct prud = new Pruduct(1, "洗髮水", "100ml"); Pruduct prud2 = new Pruduct(2, "洗面奶", "200ml"); //依次從尾部添加元素 template.opsForList().rightPush("pruduct", prud); template.opsForList().rightPush("pruduct", prud); //查詢索引0到商品總數-1索引(也就是查出所有的商品) List<Object> prodList = template.opsForList().range("pruduct", 0,template.opsForList().size("pruduct")-1); for(Object obj:prodList){ System.out.println((Pruduct)obj); } System.out.println("產品數量:"+template.opsForList().size("pruduct")); }
key和value序列化
當儲存一條資料的時候,key和value都要被序列化成json資料,取出來的時候被序列化成對象,key和value都會使用序列化器進行序列化,spring data redis提供多個序列化器
- GenericToStringSerializer:使用Spring轉換服務進行序列化;
- JacksonJsonRedisSerializer:使用Jackson 1,將對象序列化為JSON;
- Jackson2JsonRedisSerializer:使用Jackson 2,將對象序列化為JSON;
- JdkSerializationRedisSerializer:使用Java序列化;
- OxmSerializer:使用Spring O/X映射的編排器和解排器(marshaler和unmarshaler)實
- 現序列化,用於XML序列化;
- StringRedisSerializer:序列化String類型的key和value。
RedisTemplate會預設使用JdkSerializationRedisSerializer,這意味著key和value都會通過Java進行序列化。StringRedisTemplate預設會使用StringRedisSerializer
例如,假設當使用RedisTemplate的時候,我們希望將Product類型的value序列化為JSON,而key是String類型。RedisTemplate的setKeySerializer()和setValueSerializer()方法就需要如下所示:
@Bean public RedisTemplate redisTemplate(RedisConnectionFactory factory) { // 建立一個模板類 RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); // 將剛才的redis串連工廠設定到模板類中 template.setConnectionFactory(factory); // 設定key的序列化器 template.setKeySerializer(new StringRedisSerializer()); // 設定value的序列化器 //使用Jackson 2,將對象序列化為JSON Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //json轉對象類,不設定預設的會將json轉成hashmap ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); return template; }
到這裡,大家肯定會對springboot使用redis有了簡單的瞭解。
springboot緩衝某個方法申明緩衝管理器
在某些時候,我們可能有這樣的需求,使用者登入的時候,我們會從資料庫中讀取使用者所有的許可權,部門等資訊。而且每次重新整理頁面都需要判斷該使用者有沒有這個許可權,如果不停的從資料庫中讀並且計算,
是非常耗效能的,所以我們這個時候就要用到了springboot為我們帶來的緩衝管理器
首先在我們的RedisConfig這個類上加上@EnableCaching這個註解。
這個註解會被spring發現,並且會建立一個切面(aspect) 並觸發Spring緩衝註解的切點(pointcut) 。 根據所使用的註解以及緩衝的狀態, 這個切面會從緩衝中擷取資料, 將資料添加到緩衝之中或者從緩衝中移除某個值。 接下來我們需要申明一個緩衝管理器的bean,這個作用就是
@EnableCaching這個切面在新增緩衝或者刪除緩衝的時候會調用這個緩衝管理器的方法
/** * 申明緩衝管理器,會建立一個切面(aspect)並觸發Spring緩衝註解的切點(pointcut) * 根據類或者方法所使用的註解以及緩衝的狀態,這個切面會從緩衝中擷取資料,將資料添加到緩衝之中或者從緩衝中移除某個值 * @return */ @Bean public RedisCacheManager cacheManager(RedisTemplate redisTemplate) { return new RedisCacheManager(redisTemplate); }
當然,緩衝管理器除了RedisCacheManager還有一些其他的。例如
ConcurrentMapCacheManager,這個簡單的緩衝管理器使用java.util.concurrent.ConcurrentHashMap作為其緩衝儲存。它非常簡單,因此對於開發、測試或基礎的應用來講,這是一個很不錯的選擇.
添加緩衝
接下來我們在controller層的方法內加上註解,然後啟動我們的項目。
@RequestMapping("/getPrud") @Cacheable("prudCache") public Pruduct getPrud(@RequestParam(required=true)String id){ System.out.println("如果第二次沒有走到這裡說明緩衝被添加了"); return pruductDao.getPrud(Integer.parseInt(id)); }
發現列印的這段話只被列印一次,說明在走到這個方法的時候觸發了一個切面,並且尋找返回緩衝中的資料。
當然@Cacheable註解也可以放到這個dao層的方法裡面,但是這裡會報一個錯,Integer無法轉成String,因為我們dao層方法的參數類型是int,而RedisTemplate的key類型是String,這裡是要注意的。
開啟redis的用戶端發現redis對應的key就是我們的參數1,這個時候就會出問題,比如說我在其他要緩衝的方法的參數也是1,就會重複。後面我們會將自訂這個key的值。
除了@Cacheable添加緩衝外,springboot還為我們帶了了其他幾個註解
刪除緩衝
在delete的時候用@CacheEvict清楚這條緩衝。
@RequestMapping("/deletePrud") @CacheEvict("pruddeleteCache") public String deletePrud(@RequestParam(required=true)String id){ return "SUCCESS"; }
@CachePut將這個方法的傳回值放到緩衝,如果我們放一個Pruduct對象,他會將這個對象作為key,這顯然不是我們想要的。這個時候就需要自訂我們的key。
自訂key
@Cacheable和@CachePut都有一個名為key屬性,這個屬效能夠替換預設的key,它是通過一個運算式(Spel運算式,spring提供的,很簡單)計算得到的。
例如下面的就是將返回對象的id當作key來儲存(但是Pruduct的id是int類型,所以需要將數字轉化成String類型)
@RequestMapping("/savePrud") @CachePut(value="prudsaveCache",key="#result.id +''") public Pruduct savePrud(Pruduct prud){ return prud; }
另外除了#result是代表函數的傳回值,spring還為我們帶來了其他的一些中繼資料
條件化緩衝
通過為方法添加Spring的緩衝註解,Spring就會圍繞著這個方法建立一個緩衝切面。但是,在有些情境下我們可能希望將緩衝功能關閉。
@Cacheable和@CachePut提供了兩個屬性用以實現條件化緩衝:unless和condition,這兩個屬性都接受一個SpEL運算式。如果unless屬性的SpEL運算式計算結
果為true,那麼緩衝方法返回的資料就不會放到緩衝中。與之類似,如果condition屬性的SpEL運算式計算結果為false,那麼對於這個方法緩衝就會被禁用掉
表面上來看,unless和condition屬性做的是相同的事情。但是,這裡有一點細微的差別。
unless屬性只能阻止將對象放進緩衝,但是在這個方法調用的時候,依然會去緩衝中進行尋找,如果找到了匹配的值,就會返回找到的值。
與之不同,如果condition的運算式計算結果為false,那麼在這個方法調用的過程中,緩衝是被禁用的。就是說,不會去緩衝進行尋找,同時傳回值也不會放進緩衝中。
@RequestMapping("/getPrud2") @CachePut(value ="prudCache",unless="#result.desc.contains('nocache')") public Pruduct getPrud2(@RequestParam(required=true)String id){ System.out.println("如果走到這裡說明,說明緩衝沒有生效!"); Pruduct p = new Pruduct(Integer.parseInt(id), "name_nocache"+id, "nocache"); return p; }
上面的代碼中,如果返回的對象desc中包含nocache字串,則不進行緩衝。
總結demo:
將類名方法名和pruduct的id作為key
@RequestMapping("/getPrud3") @Cacheable(value ="prudCache",key="#root.targetClass.getName() + #root.methodName + #id") public Pruduct getPrud3(@RequestParam(required=true)String id){ System.out.println("如果第二次沒有走到這裡說明緩衝被添加了"); return pruductDao.getPrud(Integer.parseInt(id)); }
最後注意
#result 方法傳回值不能用在@Cacheable上,只能用在@CachePut
springboot配置升級簡單化
當然上面的配置只是為了瞭解原理的哈,實際上我們使用會更簡單點。我們重寫了RedisConfig
@Configuration@EnableCaching//開啟緩衝public class RedisConfig extends CachingConfigurerSupport { @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } /** * 申明緩衝管理器,會建立一個切面(aspect)並觸發Spring緩衝註解的切點(pointcut) * 根據類或者方法所使用的註解以及緩衝的狀態,這個切面會從緩衝中擷取資料,將資料添加到緩衝之中或者從緩衝中移除某個值 * @return */ @Bean public RedisCacheManager cacheManager(RedisTemplate redisTemplate) { return new RedisCacheManager(redisTemplate); } @Bean @Primary public RedisTemplate redisTemplate(RedisConnectionFactory factory) { // 建立一個模板類 RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); // 將剛才的redis串連工廠設定到模板類中 template.setConnectionFactory(factory); // 設定key的序列化器 template.setKeySerializer(new StringRedisSerializer()); // 設定value的序列化器 //使用Jackson 2,將對象序列化為JSON Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //json轉對象類,不設定預設的會將json轉成hashmap ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); return template; }}View Code
然後在resources下的application.properties下配置
# REDIS (RedisProperties)# Redis資料庫索引(預設為0)spring.redis.database=0 # Redis伺服器位址spring.redis.host=127.0.0.1# Redis伺服器串連連接埠spring.redis.port=6379 # Redis伺服器串連密碼(預設為空白)spring.redis.password=# 串連池最大串連數(使用負值表示沒有限制)spring.redis.pool.max-active=8 # 串連池最大阻塞等待時間(使用負值表示沒有限制)spring.redis.pool.max-wait=-1 # 串連池中的最大空閑串連spring.redis.pool.max-idle=8 # 串連池中的最小空閑串連spring.redis.pool.min-idle=0 # 連線逾時時間(毫秒)spring.redis.timeout=0View Code
大家發現我們並沒有註冊RedisConnectionFactory,那是因為spring預設幫我們讀取application.properties檔案並且註冊了一個factorybean
keyGenerator方法幫我們註冊了一個key的建置規則,就不用我們寫spel運算式了,根據反射的原理讀取類名+方法名+參數。但是我們有時候還是需要結合spel的。
然後在controller上加上@Cacheable("cachename"),之後就可以在redis看到儲存了並且key的值是keyGenerator產生的名字
本文代碼github地址