您的位置:首页 > 数据库 > Redis

Spring Boot 连接 redis 集群

2018-02-04 19:27 661 查看
最近一直在画小程序的界面,感觉自己都快成为一个前端工程师了,尤其是前面做管理后台的时候使用Angular4,让自己有点头大。都快忘记自己是Java开发了。。。上周自己在三台服务器上面搭建了一个redis集群,每台服务器创建三个实例,端口分别是7000,7001,7002.....7008。搭建过程中遇到的一个问题就是centos 7配置ruby最高配置2.0.0的版本,需要用rvm来更新ruby。

首先看一下redis 集群的目的是做什么:

随着企业数据量的增多,Redis不论作为数据存储或是缓存,它的数据量也会逐渐增多,虽然Redis的速度非常可观,但随着其中的数据量的庞大,并且仅仅在一个设备或是一个Redis实例中,其存取速度也会大打折扣,所以我们需要在不同的设备或服务器上,搭建多个Redis实例仓库,将原来的Redis的所有的keys分发到各个服务器的Redis上,这就是现在所谓的Redis集群(Redis Cluster)。

Redis集群中使用哈希槽来存储客户端的keys,而在Redis中,目前存在16384个哈希槽,它们被全部分配给所有的节点。

ok 在前面我已经搭建好集群的环境。

既然环境搭建好了,那就用Spring Boot(已经爱上这个框架了,虽然公司仍然还在用Spring MVC,Spring,Mybatis)简单连接一下。

IDEA新建一个Spring Boot项目,在新建过程中,选中Nosql中的redis,这样pom文件会自动集成redis。

配置文件中:(简单配置一下)

spring.redis.cluster.nodes=115.xxx.xx.xxx:7000,115.xxx.xx.xxx:7001,...,111.xxx.xxx.xx:7008
spring.redis.password=password

单元测试(Spring Boot 项目下有test文件夹)

package com.example.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

@Autowired
RedisTemplate<String,String> redisTemplate;
@Test
public void contextLoads() {
}
@Test
public void test(){
ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
opsForValue.set("redisKey","cluster test");
System.out.println("11"+opsForValue.get("test"));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: