SpringBoot整合Redis、和Redis集群

一、SpringBoot整合Redis

步骤:1.添加依赖:



   org.springframework.boot
   spring-boot-starter-data-redis



   redis.clients
   jedis
   2.9.0

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 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,系统缓存的时候,看哪个闲着就优先使用谁存储,这样就实现了更快的速度存储了。

展开阅读全文

更新时间:2025-04-29

标签:集群   注解   节点   缓存   闲着   单机   频繁   对象   方法   科技   信息

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020- All Rights Reserved. Powered By bs178.com 闽ICP备11008920号
闽公网安备35020302034844号

Top