本文主要內容:springBoot簡介,在SpringBoot中如何集成Redis,可配置Redis集羣。java
你想要的,這裏都有:https://spring.io/projects/spring-boot 這是SpringBoot的官方文檔,開發者已經將你須要的東西都給你了。SpringBoot是一個大的容器,能夠在這裏很輕鬆地建立各類Spring應用,而且輕鬆集成其餘框架,能夠參照官網的案例完成一個HelloWorld。完成以後你會發現使用SpringBoot是一件多麼優雅的事情。node
parent groupId:org.springframework.boot artifactId:spring-boot-starter-parent version:2.0.0.RELEASE dependencies groupId: org.springframework.boot artifactId: spring-boot-starter build plugins plugin groupId: org.springframework.boot artifactId: spring-boot-maven-plugin
@SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
你只須要寫一個main()方法就能夠直接啓動你的項目,默認在8080端口啓動。比起使用傳統的SSM那一套要簡單許多,這是由於SpringBoot的設計之禪就是默認優於配置,所以它內置了不少默認的配置,包括Tomcat。可是它並不適合初學者使用。過分的封裝致使開發者沒法接觸底層。git
官網:https://redis.io/redis
基於內存的鍵值對數據庫,能夠分佈式部署,經常使用做緩存。缺點就是不一樣版本之間差別較大。本文中提到的Redis是4.x。spring
操做Redis數據庫有一套Jedis JavaAPI。這裏使用SpringBoot集成就須要安裝它的方式來配置。因爲SpringBoot自己集成了許多框架,實質上這裏就是使用了Jedis。數據庫
首先須要引入maven依賴緩存
groupId: redis.clients artifactId: jedis version: 2.9.0 ------ groupId: org.springframework.data artifactId: spring-data-redis version: 2.0.5.RELEASE
在默認的yml中配置。springboot
spring: #配置redis redis: cluster: nodes: 192.168.64.120:7000, 192.168.64.120:7001, 192.168.64.120:7002, 192.168.64.120:7003, 192.168.64.120:7004, 192.168.64.120:7005 max-redirects: 3 timeout: 5000 jedis: pool: max-active: 10 min-idle: 1 max-wait: -1ms max-idle: 8
這裏的RedisTemplate就是SpringBoot提供操做Redis的接口類,實際上就是在Jedis基礎上的二次封裝。mybatis
@Service public class RedisService { @Autowired private RedisTemplate redisTemplate; /** * 寫入緩存設置時效時間 * @param key * @param value * @return */ public boolean set(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 刪除對應的value * @param key */ public void remove(final String key) { if (exists(key)) { redisTemplate.delete(key); } } /** * 判斷緩存中是否有對應的value * @param key * @return */ public boolean exists(final String key) { return redisTemplate.hasKey(key); } /** * 讀取緩存 * @param key * @return */ public Object get(final String key) { Object result = null; ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); result = operations.get(key); return result; } ... }
這裏只給出了部分代碼,所有代碼參考:https://gitee.com/Yao_Qi/springboot_integrates_mybatis_and_rediscluster框架