1. 程式人生 > >Spring Boot 中的redis使用

Spring Boot 中的redis使用

步驟一:匯入依賴包

<!-- redis 快取 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-redis</artifactId>
</dependency>
步驟二:

1. 單機版

在application.properties配置中加入

#spring.redis.host=192.168.0.111
#spring.redis.port=8023
在spring boot 的啟動類中開啟redis 快取
@SpringBootApplication
// 開啟redis 快取 //@EnableCaching public class SpringDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringDemoApplication.class, args); } }
開啟快取後就可以使用了:在需要用到快取的地方加上註解即可
@Cacheable(value = "addUser")
/**
     * @Cacheable redis 快取
     * @param user
*/
//    @Cacheable(value = "addUser")
public void addUser(User user) { userMapper.addUser(user); }

2. redis 叢集

在在application.properties配置中加入

#整合redis 叢集
#spring.redis.cluster.nodes=192.168.0.108:7001,192.168.0.108:7002,192.168.0.108:7003,192.168.0.108:7004
寫一個配置檔案用來分解以上叢集節點
//@Configuration
//public class RedisConfig {
//
//    @Value("${spring.redis.cluster.nodes}")
// private String clusterNodes; // // /** // * 注入叢集節點資訊 // * @return // */ // @Bean // 相當於<bean> // public JedisCluster getJedisCluster(){ // // // 分割叢集節點 // String[] strings = clusterNodes.split(","); // // Set<HostAndPort> hostAndPorts = new HashSet<HostAndPort>(); // // // 迴圈叢集節點物件 // for (String node : strings) { // String[] hp = node.split(":"); // // hostAndPorts.add(new HostAndPort(hp[0],Integer.parseInt(hp[1]))); // } // // // // JedisCluster jedisCluster = new JedisCluster(hostAndPorts); // // return jedisCluster; // } //}

使用的時候注入以下即可:

@Autowired
//    private JedisCluster jedisCluster;

//    public String findRedis(){
//        jedisCluster.set("name","sfsd");
//        String value = jedisCluster.get("name");
//
//        return value;
//    }