SpringBoot整合Redis、和Redis叢集
阿新 • • 發佈:2018-12-02
一、SpringBoot整合Redis
步驟:1.新增依賴:
<!--redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
2.application.properties新增Redis的連結資訊:
#單個Redis #spring.redis.host=127.0.0.1 #spring.redis.port=6379
3.springboot啟動類新增快取註解:@EnableCaching
4.在需要快取的地方使用:@Cacheable(value = "findAllUser")
一般在頻繁查詢的方法裡面裡面使用,value則是key值。
哇,真的就幾句話就實現了Redis的快取了。
二、SpringBoot整合Redis叢集
1.application.properties新增置Redis叢集的資訊:
#redis叢集 模擬4個Redis叢集節點 spring.redis.cluster.nodes=127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003,127.0.0.1:7004
2.springboot裡面新增Redis叢集的配置:
package com.zero.learn_spring_boot.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import java.util.HashSet; import java.util.Set; /** * Created by 81046 on 2018-08-30 */ @Configuration public class RedisConfig { @Value("${spring.redis.cluster.nodes}") private String clusterNodes; @Bean public JedisCluster getJedisCluster(){ //分割叢集節點 String[] cNodes = clusterNodes.split(","); //建立set集合物件 Set<HostAndPort> nodes =new HashSet<>(); for (String node:cNodes) { //127.0.0.1:7001 String[] hp = node.split(":"); nodes.add(new HostAndPort(hp[0],Integer.parseInt(hp[1]))); } //建立Redis叢集物件 JedisCluster jedisCluster=new JedisCluster(nodes); return jedisCluster; } }
3.在service裡面使用該叢集:
@Autowired private JedisCluster jedisCluster; @Override public String findRedis(){ jedisCluster.set("username","倚天屠龍記"); return jedisCluster.get("username"); }
4.在controller裡面訪問該方法:
@GetMapping("/findRedis") public String findRedis(){ return userServiceMyBatis.findRedis(); }
自此實現了Redis的叢集。
下面純屬個人謊言,勿看:
到現在我自己感覺,叢集就是相當於有多個單機的Redis,系統快取的時候,看哪個閒著就優先使用誰儲存,這樣就實現了更快的速度儲存了。