文章出處

寫入redis

讀取redis

存入數據

讀取數據

第一次,走數據庫而非緩存
SpringBoot_03_Redis:SpringBoot添加redis支持非常簡單,已經做好了starter。
org.springframework.boot spring-boot-starter-data-redis
相關配置
只需要在application.properties文件中配置redis參數即可。
# REDIS (RedisProperties)# Redis數據庫索引(默認為0)spring.redis.database=0# Redis服務器地址spring.redis.host=localhost# 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=0
使用
通過以上配置,即可使用redis讀寫數據。
@RestController@RequestMapping("redis/string")public class StringRedisController { @Autowired private StringRedisTemplate stringRedisTemplate; @Resource(name = "stringRedisTemplate") private ValueOperationsvalOpsStr; @RequestMapping("set") public String setKeyAndValue(String key, String value){ valOpsStr.set(key, value); return key + ": " + value; } @RequestMapping("get") public String getKey(String key){ return valOpsStr.get(key); }} ,>
通過注入StringRedisTemplate,即可訪問reids。

寫入redis

讀取redis
添加cache的配置類
@Configuration@EnableCachingpublic 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(); } }; } @SuppressWarnings("rawtypes") @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); //設置緩存過期時間 rcm.setDefaultExpiration(5); // 秒 return rcm; }}
通過注解使用緩存
@RestController@RequestMapping("redis/object")public class ObjectRedisController { @Autowired private PersonDao personDao; @RequestMapping("/setPerson") public String set(String id, String name,Integer age){ Person person = new Person(id, name, age); personDao.save(person); return person.toString(); } @RequestMapping("/getPerson") @Cacheable(value="user-key") public Person getPerson(String id){ System.out.println("從數據庫獲取"); return personDao.getPerson(id); }}

存入數據

讀取數據

第一次,走數據庫而非緩存
第二次訪問,則不打印“從數據庫獲取”,因為注解@Cacheable,使的數據從redis緩存中直接獲取;5s過后,再次訪問則又走數據庫,因為在config中設置了緩存失效時間為5s。看文倉www.kanwencang.com網友整理上傳,為您提供最全的知識大全,期待您的分享,轉載請注明出處。
歡迎轉載:http://www.kanwencang.com/bangong/20170126/95348.html
文章列表
全站熱搜