Redis下载地址:http://redis.io/download
1.上传redis-3.2.1.tar.gz到虚拟机的/opt目录并解压
tar -zxvf redis-3.2.1.tar.gz
cd redis-3.2.1
2.如果没有安装gcc命令,请先安装gcc
yum install gcc
3.执行make命令
make
4.防火墙开放6379端口
/sbin/iptables -I INPUT -p tcp --dport 6379 -j ACCEPT
service iptables save
5.修改redis.conf配置文件,绑定IP和设置密码
bind 192.168.1.216
requirepass 123456
6.启动redis服务,并测试
cd src
./redis-server /opt/redis/redis-3.2.1/redis.conf
登陆redis
./redis-cli -h 192.168.1.216 -a 123456
192.168.1.216:6379> set test 123
OK
192.168.1.216:6379> get test
"123"
7.JAVA客户端代码
jdbc.properties文件:
redis.url=192.168.1.216
redis.port=6379
redis.password=123456
applicationContext.xml文件
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>jdbc.properties</value>
</list>
</property>
</bean>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="minIdle" value="10" />
<property name="maxIdle" value="50" />
<property name="maxTotal" value="100" />
<property name="testOnReturn" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testWhileIdle" value="true" />
</bean>
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="jedisPoolConfig"/>
<constructor-arg index="1" value="${redis.url}"/>
<constructor-arg index="2" value="${redis.port}" type="int"/>
<constructor-arg index="3" value="1000" type="int"/>
<constructor-arg index="4" value="${redis.password}" />
</bean>
<bean id="redisClient" class="com.company.test.redis.RedisClient">
<property name="jedisPool" ref="jedisPool"></property>
</bean>
JAVA类
public class RedisClient {
private JedisPool jedisPool;
public void set(){
for (int i = 0; i < 10; i++) {
Jedis jedis = jedisPool.getResource();
jedis.set(String.valueOf(i),"test"+i);
}
}
public void get(){
for (int i = 0; i < 10; i++) {
Jedis jedis = jedisPool.getResource();
String str = jedis.get(String.valueOf(i));
System.out.println(str);
}
}
public JedisPool getJedisPool() {
return jedisPool;
}
public void setJedisPool(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
}
新建测试类
public class RedisClientTest {
private ClassPathXmlApplicationContext cfx;
@Before
public void load(){
this.cfx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void test() throws InterruptedException {
RedisClient redisClient= (RedisClient) cfx.getBean("redisClient");
redisClient.set();
Thread.sleep(1000);
redisClient.get();
}
}
执行结果:
test0
test1
test2
test3
test4
test5
test6
test7
test8
test9
后台redis服务:
192.168.1.216:6379> get 0
"test0"
192.168.1.216:6379> get 1
"test1"
192.168.1.216:6379>