一丶環(huán)境準(zhǔn)備
- VMware Linux CentOS-6.5。
- redis-3.0.0.tar.gz包
- 上傳工具FileZilla Client
- Redis是c語言開發(fā)的。安裝redis需要c語言的編譯環(huán)境。如果沒有g(shù)cc需要聯(lián)網(wǎng)(虛擬機(jī)聯(lián)網(wǎng)請自行百度,稍后我也會(huì)寫一篇文章介紹虛擬機(jī)聯(lián)網(wǎng)配置)在線安裝。Linux命令行執(zhí)行:
yum install gcc-c++
二丶安裝redis
第一步:上傳。使用FileZilla Client將redis的源碼包上傳到linux系統(tǒng)。并解壓。

第二步:編譯。進(jìn)入redis源碼目錄。make

第四步:安裝。make install PREFIX=/usr/local/redis
PREFIX參數(shù)指定redis的安裝目錄。一般軟件安裝到/usr目錄下

第五步:啟動(dòng)。

第六步前端啟動(dòng)

第七步后端啟動(dòng):需要復(fù)制配置文件并修改


將redis.conf文件中的 daemonize 改為yes。

后端啟動(dòng)

查看redis進(jìn)程

三丶使用redis-cli
[root@cehae bin]# ./redis-cli
默認(rèn)連接localhost運(yùn)行在6379端口的redis服務(wù)。
[root@cehae bin]# ./redis-cli -h 192.168.25.200 -p 6379
-h:連接的服務(wù)器的地址
-p:服務(wù)的端口號

注意存儲(chǔ)中文時(shí)出現(xiàn)亂碼??梢酝顺龊笫褂?br> ./redis-cli -h 192.168.25.200 -p 6379 --raw 啟動(dòng)

關(guān)閉redis
方式一

方式二:使用Linux殺死進(jìn)程命令
kill -9 進(jìn)程號 強(qiáng)制退出(如果運(yùn)行出錯(cuò),可以使用強(qiáng)制退出)
kill 進(jìn)程號 讓進(jìn)程正常退出(讓進(jìn)程處理完后退出)
四丶搭建redis集群
redis集群原理
redis-cluster架構(gòu)圖

redis容錯(cuò)機(jī)制:投票

架構(gòu)細(xì)節(jié):
(1)所有的redis節(jié)點(diǎn)彼此互聯(lián)(PING-PONG機(jī)制),內(nèi)部使用二進(jìn)制協(xié)議優(yōu)化傳輸速度和帶寬。
(2)節(jié)點(diǎn)的fail是通過集群中超過半數(shù)的節(jié)點(diǎn)檢測失效時(shí)才生效。
(3)客戶端與redis節(jié)點(diǎn)直連,不需要中間proxy層.客戶端不需要連接集群所有節(jié)點(diǎn),連接集群中任何一個(gè)可用節(jié)點(diǎn)即可。
(4)redis-cluster把所有的物理節(jié)點(diǎn)映射到[0-16383]slot上,cluster 負(fù)責(zé)維護(hù)node<->slot<->value。
Redis 集群中內(nèi)置了 16384 個(gè)哈希槽,當(dāng)需要在 Redis 集群中放置一個(gè) key-value 時(shí),redis 先對 key 使用 crc16 算法算出一個(gè)結(jié)果,然后把結(jié)果對 16384 求余數(shù),這樣每個(gè) key 都會(huì)對應(yīng)一個(gè)編號在 0-16383 之間的哈希槽,redis 會(huì)根據(jù)節(jié)點(diǎn)數(shù)量大致均等的將哈希槽映射到不同的節(jié)點(diǎn)。

搭建集群
說明:
由于投票機(jī)制redis集群中至少應(yīng)該有三個(gè)節(jié)點(diǎn),同時(shí)要保證集群的高可用,需要每個(gè)節(jié)點(diǎn)有一個(gè)備份機(jī)。因此redis集群至少需要6臺服務(wù)器。在這我只搭建偽分布式,使用一臺虛擬機(jī)運(yùn)行6個(gè)redis實(shí)例。對應(yīng)6個(gè)redis實(shí)例的端口號為7001-7006。
第一步:使用ruby腳本搭建集群。
需要ruby的運(yùn)行環(huán)境。安裝ruby
yum install ruby
yum install rubygems
第二步:安裝ruby腳本運(yùn)行使用的包
[root@cehae ~]# gem install redis-3.0.0.gem
Successfully installed redis-3.0.0
1 gem installed
Installing ri documentation for redis-3.0.0...
Installing RDoc documentation for redis-3.0.0...
[root@cehae ~]#
redis-trib.rb腳本
[root@cehae ~]# cd redis-3.0.0/src
[root@cehae src]# ll *.rb
-rwxrwxr-x. 1 root root 48141 Apr 1 2015 redis-trib.rb

第三步:創(chuàng)建redis-cluster目錄。并將/usr/local/redis下的bin目錄復(fù)制6份至redis-cluster下面。



第四步:修改配置文件。每個(gè)實(shí)例運(yùn)行在不同的端口,需要修改redis.conf配置文件。配置文件中還需要把cluster-enabled yes前的注釋去掉。

修改端口

去掉# cluster-enabled yes 中的注釋

第五步:編寫啟動(dòng)redis腳本并使用ruby腳本搭建集群。

啟動(dòng)腳本

cd redis01
./redis-server redis.conf
cd ..
cd redis02
./redis-server redis.conf
cd ..
cd redis03
./redis-server redis.conf
cd ..
cd redis04
./redis-server redis.conf
cd ..
cd redis05
./redis-server redis.conf
cd ..
cd redis06
./redis-server redis.conf
注意創(chuàng)建完畢后并沒有執(zhí)行的權(quán)限,因此需要修改腳本權(quán)限

啟動(dòng)6個(gè)redis

使用ruby腳本搭建集群
./redis-trib.rb create --replicas 1 192.168.25.200:7001 192.168.25.200:7002 192.168.25.200:7003 192.168.25.200:7004 192.168.25.200:7005 192.168.25.200:7006

輸入yes

搭建成功,槽以及主機(jī)備份機(jī)也自動(dòng)設(shè)置完畢。

[root@cehae redis-cluster]# ./redis-trib.rb create --replicas 1 192.168.25.200:7001 192.168.25.200:7002 192.168.25.200:7003 192.168.25.200:7004 192.168.25.200:7005 192.168.25.200:7006
>>> Creating cluster
Connecting to node 192.168.25.200:7001: OK
Connecting to node 192.168.25.200:7002: OK
Connecting to node 192.168.25.200:7003: OK
Connecting to node 192.168.25.200:7004: OK
Connecting to node 192.168.25.200:7005: OK
Connecting to node 192.168.25.200:7006: OK
>>> Performing hash slots allocation on 6 nodes...
Using 3 masters:
192.168.25.200:7001
192.168.25.200:7002
192.168.25.200:7003
Adding replica 192.168.25.200:7004 to 192.168.25.200:7001
Adding replica 192.168.25.200:7005 to 192.168.25.200:7002
Adding replica 192.168.25.200:7006 to 192.168.25.200:7003
M: 2e48ae301e9c32b04a7d4d92e15e98e78de8c1f3 192.168.25.200:7001
slots:0-5460 (5461 slots) master
M: 8cd93a9a943b4ef851af6a03edd699a6061ace01 192.168.25.200:7002
slots:5461-10922 (5462 slots) master
M: 2935007902d83f20b1253d7f43dae32aab9744e6 192.168.25.200:7003
slots:10923-16383 (5461 slots) master
S: 74f9d9706f848471583929fc8bbde3c8e99e211b 192.168.25.200:7004
replicates 2e48ae301e9c32b04a7d4d92e15e98e78de8c1f3
S: 42cc9e25ebb19dda92591364c1df4b3a518b795b 192.168.25.200:7005
replicates 8cd93a9a943b4ef851af6a03edd699a6061ace01
S: 8b1b11d509d29659c2831e7a9f6469c060dfcd39 192.168.25.200:7006
replicates 2935007902d83f20b1253d7f43dae32aab9744e6
Can I set the above configuration? (type 'yes' to accept): yes
>>> Nodes configuration updated
>>> Assign a different config epoch to each node
>>> Sending CLUSTER MEET messages to join the cluster
Waiting for the cluster to join.....
>>> Performing Cluster Check (using node 192.168.25.200:7001)
M: 2e48ae301e9c32b04a7d4d92e15e98e78de8c1f3 192.168.25.200:7001
slots:0-5460 (5461 slots) master
M: 8cd93a9a943b4ef851af6a03edd699a6061ace01 192.168.25.200:7002
slots:5461-10922 (5462 slots) master
M: 2935007902d83f20b1253d7f43dae32aab9744e6 192.168.25.200:7003
slots:10923-16383 (5461 slots) master
M: 74f9d9706f848471583929fc8bbde3c8e99e211b 192.168.25.200:7004
slots: (0 slots) master
replicates 2e48ae301e9c32b04a7d4d92e15e98e78de8c1f3
M: 42cc9e25ebb19dda92591364c1df4b3a518b795b 192.168.25.200:7005
slots: (0 slots) master
replicates 8cd93a9a943b4ef851af6a03edd699a6061ace01
M: 8b1b11d509d29659c2831e7a9f6469c060dfcd39 192.168.25.200:7006
slots: (0 slots) master
replicates 2935007902d83f20b1253d7f43dae32aab9744e6
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.
[root@cehae redis-cluster]#
第六步:連接和關(guān)閉集群
連接任意一個(gè)節(jié)點(diǎn)就連接到了集群,注意一定要加 -c,-c代表連接的是集群,否則只是連接單個(gè)redis。
[root@cehae redis-cluster]# redis01/redis-cli -p 7001 -c
注意下圖 set d test 并沒有存放在redis01上面,而是通過crc16算法再對16384 取余計(jì)算得到結(jié)果,將結(jié)果與槽對比,分配到了redis03上面,證明集群搭建成功。


編寫關(guān)閉集群腳本

redis01/redis-cli -p 7001 shutdown
redis02/redis-cli -p 7002 shutdown
redis03/redis-cli -p 7003 shutdown
redis04/redis-cli -p 7004 shutdown
redis05/redis-cli -p 7005 shutdown
redis06/redis-cli -p 7006 shutdown
同樣注意賦予執(zhí)行權(quán)限。

關(guān)閉集群

使用jedis連接集群
創(chuàng)建Maven工程,將jedis和junit的坐標(biāo)添加到pom文件中然后編寫測試代碼:
@Test
public void testJedisCluster() throws Exception {
// 第一步:使用JedisCluster對象。需要一個(gè)Set<HostAndPort>參數(shù)。Redis節(jié)點(diǎn)的列表。
Set<HostAndPort> nodes = new HashSet<>();
nodes.add(new HostAndPort("192.168.25.200", 7001));
nodes.add(new HostAndPort("192.168.25.200", 7002));
nodes.add(new HostAndPort("192.168.25.200", 7003));
nodes.add(new HostAndPort("192.168.25.200", 7004));
nodes.add(new HostAndPort("192.168.25.200", 7005));
nodes.add(new HostAndPort("192.168.25.200", 7006));
JedisCluster jedisCluster = new JedisCluster(nodes);
// 第二步:直接使用JedisCluster對象操作redis。在系統(tǒng)中單例存在。
jedisCluster.set("hello", "100");
String result = jedisCluster.get("hello");
// 第三步:打印結(jié)果
System.out.println(result);
// 第四步:系統(tǒng)關(guān)閉前,關(guān)閉JedisCluster對象。
jedisCluster.close();
}
安裝所需要的資料可以自行下載,也可以去我GitHub下面下載。歡迎star,轉(zhuǎn)載請私聊,謝謝。
SpringDataRedis的使用
搭建工程引入依賴
<!-- 集中定義依賴版本號 -->
<properties>
<spring.version>4.2.4.RELEASE</spring.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 測試 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<!-- redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
</dependencies>
配置文件
在src/main/resources下創(chuàng)建 properties/redis-config.properties 目錄以及文件
# Redis settings
# server IP
redis.host=192.168.25.200
# server port
redis.port=6379
# server pass
redis.pass=
# use dbIndex
redis.database=0
# 控制一個(gè)pool最多有多少個(gè)狀態(tài)為idle(空閑的)的jedis實(shí)例
redis.maxIdle=300
# 表示當(dāng)borrow(引入)一個(gè)jedis實(shí)例時(shí),最大的等待時(shí)間,如果超過等待時(shí)間(毫秒),則直接拋出JedisConnectionException;
redis.maxWait=3000
# 在borrow一個(gè)jedis實(shí)例時(shí),是否提前進(jìn)行validate操作;如果為true,則得到的jedis實(shí)例均是可用的
redis.testOnBorrow=true
在src/main/resources下創(chuàng)建 spring/applicationContext-redis.xml 目錄以及文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<context:property-placeholder location="classpath*:properties/*.properties" />
<!-- redis 相關(guān)配置 -->
<!-- 連接池 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!-- 連接工廠 -->
<bean id="JedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"
p:pool-config-ref="poolConfig" />
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="JedisConnectionFactory" />
</bean>
</beans>
編寫測試代碼
TestValue.java
package com.cehae.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestValue {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void setValue() {
redisTemplate.boundValueOps("name").set("cehae");
}
@Test
public void getValue() {
String str = (String) redisTemplate.boundValueOps("name").get();
System.out.println(str);
}
@Test
public void deleteValue() {
redisTemplate.delete("name");
}
}
TestHash.java
package com.cehae.test;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestHash {
@Autowired
private RedisTemplate redisTemplate;
public void testSetValue() {
redisTemplate.boundHashOps("namehash").put("a", "劉備");
redisTemplate.boundHashOps("namehash").put("b", "關(guān)羽");
redisTemplate.boundHashOps("namehash").put("c", "張飛");
redisTemplate.boundHashOps("namehash").put("d", "趙云");
}
public void testGetKeys() {
Set s = redisTemplate.boundHashOps("namehash").keys();
System.out.println(s);
}
public void testGetValues() {
List values = redisTemplate.boundHashOps("namehash").values();
System.out.println(values);
}
public void testGetValueByKey() {
Object object = redisTemplate.boundHashOps("namehash").get("b");
System.out.println(object);
}
public void testRemoveValueByKey() {
redisTemplate.boundHashOps("namehash").delete("c");
}
}
TestList.java
package com.cehae.test;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestList {
@Autowired
private RedisTemplate redisTemplate;
/**
* 右壓棧:后添加的對象排在后邊
*
* 劉備 關(guān)羽 張飛
*/
public void testSetValue1() {
redisTemplate.boundListOps("namelist1").rightPush("劉備");
redisTemplate.boundListOps("namelist1").rightPush("關(guān)羽");
redisTemplate.boundListOps("namelist1").rightPush("張飛");
}
/**
* 顯示右壓棧集合
*
* 劉備 關(guān)羽 張飛
*/
public void testGetValue1() {
List list = redisTemplate.boundListOps("namelist1").range(0, 10);
System.out.println(list);
}
/**
* 左壓棧:后添加的對象排在前邊
*
* 張飛 關(guān)羽 劉備
*/
public void testSetValue2() {
redisTemplate.boundListOps("namelist2").leftPush("劉備");
redisTemplate.boundListOps("namelist2").leftPush("關(guān)羽");
redisTemplate.boundListOps("namelist2").leftPush("張飛");
}
/**
* 顯示左壓棧集合
*
* 張飛 關(guān)羽 劉備
*/
public void testGetValue2() {
List list = redisTemplate.boundListOps("namelist2").range(0, 10);
System.out.println(list);
}
/**
* 查詢集合某個(gè)元素 index是從左到右取(從0開始),-數(shù)是從右向左(從1開始)
*/
public void testSearchByIndex() {
String s = (String) redisTemplate.boundListOps("namelist2").index(-3);
System.out.println(s);
}
/**
* 移除集合某個(gè)元素
*/
public void testRemoveByIndex() {
redisTemplate.boundListOps("namelist1").remove(1, "關(guān)羽");
}
/**
* 移除key
*/
public void testRemoveKey() {
redisTemplate.delete("namelist1");
redisTemplate.delete("namelist2");
}
}
TestSet.java
package com.cehae.test;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestSet {
@Autowired
private RedisTemplate redisTemplate;
/**
* 存入值
*/
public void setValue() {
redisTemplate.boundSetOps("nameset").add("曹操");
redisTemplate.boundSetOps("nameset").add("劉備");
redisTemplate.boundSetOps("nameset").add("孫權(quán)");
}
/**
* 提取值
*/
public void getValue() {
Set members = redisTemplate.boundSetOps("nameset").members();
System.out.println(members);
}
/**
* 刪除集合中的某一個(gè)值
*/
public void deleteValue() {
redisTemplate.boundSetOps("nameset").remove("孫權(quán)");
}
/**
* 刪除整個(gè)集合
*/
public void deleteAllValue() {
redisTemplate.delete("nameset");
}
}