相關redis的概述,參見Nosql章節html
redisTemplate的介紹,參考:http://blog.csdn.net/ruby_one/article/details/79141940java
StringRedisTemplate做爲RedisTemplate的子類,只支持KV爲String的操做node
StringRedisTemplate與RedisTemplate
二者的關係是StringRedisTemplate繼承RedisTemplate。
二者的數據是不共通的;也就是說StringRedisTemplate只能管理StringRedisTemplate裏面的數據,
RedisTemplate只能管理RedisTemplate中的數據。
SDR默認採用的序列化策略有兩種,一種是String的序列化策略,一種是JDK的序列化策略。
StringRedisTemplate默認採用的是String的序列化策略,保存的key和value都是採用此策略序列化保存的。
RedisTemplate默認採用的是JDK的序列化策略,保存的key和value都是採用此策略序列化保存的。
更多文檔,參考javadoc:點擊查看mysql
其餘實戰:參考碼雲springboot全家桶等!linux
1.安裝windows版redisgit
因爲windows的redis僅僅用於我的測試玩耍,這裏就簡單下載zip解壓版本,相關配置項也不在這裏贅述,參考linux下redis的介紹github
點擊下載:https://github.com/MicrosoftArchive/redis/releasesredis
下載後解壓;spring
在解壓所在目錄使用以下命令啓動服務端:(因爲這裏使用的win10的powershell,因此須要添加./,或者配置環境變量也能夠避免使用./)sql
./redis-server.exe redis.windows.conf
// 這裏就不將其註冊爲windows服務了,關閉窗口,也就關閉了redis
啓動命令端:
./redis-cli.exe -h 127.0.0.1 -p 6379
2.引入依賴
<!-- springboot整合redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
這裏只需引入這一個redis的依賴便可,其餘3個自動進行了依賴:
3.在application.yml中配置redis
#redis
spring.redis.hostName=127.0.0.1 spring.redis.port=6379 spring.redis.pool.maxActive=8 spring.redis.pool.maxWait=-1 spring.redis.pool.maxIdle=8 spring.redis.pool.minIdle=0 spring.redis.timeout=0
// yml中改成yml的寫法:
# redis配置,如下有默認配置的也可使用默認配置
redis:
host: 127.0.0.1
port: 6379
pool:
max-active: 8
max-wait: 1
max-idle: 8
min-idle: 0
timeout: 0
// 有許多的默認配置,能夠直接使用默認
若是換成了集羣方式,配置修改入以下所示:
spring:
application:
name: spring-boot-redis
redis:
host: 192.168.145.132
port: 6379
timeout: 20000
cluster:
nodes: 192.168.211.134:7000,192.168.211.134:7001,192.168.211.134:7002
maxRedirects: 6
pool:
max-active: 8
min-idle: 0
max-idle: 8
max-wait: -1
// 對應的配置類:org.springframework.boot.autoconfigure.data.redis.RedisProperties
4.創建redis配置類
package com.example.demo.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * redis配置類 * * @author zcc ON 2018/3/19 **/ @Configuration @EnableCaching//開啓註解
public class RedisConfig { @Bean public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) { CacheManager cacheManager = new RedisCacheManager(redisTemplate); return cacheManager; /*RedisCacheManager rcm = new RedisCacheManager(redisTemplate); // 多個緩存的名稱,目前只定義了一個 rcm.setCacheNames(Arrays.asList("thisredis")); //設置緩存默認過時時間(秒) rcm.setDefaultExpiration(600); return rcm;*/ } // 如下兩種redisTemplate自由根據場景選擇
@Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); //使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值(默認使用JDK的序列化方式)
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper(mapper); template.setValueSerializer(serializer); //使用StringRedisSerializer來序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) { StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(); stringRedisTemplate.setConnectionFactory(factory); return stringRedisTemplate; } }
5.編寫相關的實體類
這裏注意必定要實現序列化接口用於序列化!
public class Girl implements Serializable{ private static final long serialVersionUID = -3946734305303957850L;
// IDEA開啓Java的檢查便可自動生成!
6.相關的service
處理緩存相關的前綴的常量類:
public class RedisKeyPrefix { private RedisKeyPrefix() { } public static final String GIRL = "girl:"; }
/** * 經過id查詢,若是查詢到則進行緩存 * @param id 實體類id * @return 查詢到的實現類 */
public Girl findOne(Integer id) { String key = RedisKeyPrefix.GIRL + id; // 緩存存在
boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { // 從緩存中取
Girl girl = redisTemplate.opsForValue().get(key); log.info("從緩存中獲取了用戶!"); return girl; } // 從數據庫取,並存回緩存
Girl girl = girlRepository.findOne(id); // 放入緩存,並設置緩存時間
redisTemplate.opsForValue().set(key, girl, 600, TimeUnit.SECONDS); return girl; }
特別注意的是這裏的注入,因爲以前配置了redisTemplate及其子類,故須要使用@Resource註解進行!
@Resource private RedisTemplate<String, Girl> redisTemplate; // private RedisTemplate<String, Object> redisTemplate;根據實際狀況取泛型
剩下的刪除和更新也是對應的操做緩存,參考網友的寫法:
/** * 更新用戶 * 若是緩存存在,刪除 * 若是緩存不存在,不操做 * * @param user 用戶 */
public void updateUser(User user) { logger.info("更新用戶start..."); userMapper.updateById(user); int userId = user.getId(); // 緩存存在,刪除緩存
String key = "user_" + userId; boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { redisTemplate.delete(key); logger.info("更新用戶時候,從緩存中刪除用戶 >> " + userId); } } /** * 刪除用戶 * 若是緩存中存在,刪除 */
public void deleteById(int id) { logger.info("刪除用戶start..."); userMapper.deleteById(id); // 緩存存在,刪除緩存
String key = "user_" + id; boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { redisTemplate.delete(key); logger.info("刪除用戶時候,從緩存中刪除用戶 >> " + id); } }
更多基本用法,參考:http://blog.csdn.net/ruby_one/article/details/79141940
1.數據同步問題
redis和mysql數據的同步,代碼級別大體能夠這樣作: 讀: 讀redis->沒有,讀mysql->把mysql數據寫回redis 寫: 寫mysql->成功,寫redis
2.統一管理key 前綴
經過常量類的形式(阿里的解決方案),固然,經過配置properties 等也是闊以的
3.開發規範
參考nosql 入門章節介紹