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;
//    }




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值