2019独角兽企业重金招聘Python工程师标准>>>
1. 环境准备
安装编译所需要的包:
yum install gcc tcl
2. 下载redis
http://download.redis.io/releases/redis-3.2.7.tar.gz
3. 安装redis
## 创建redis的安装目录
mkdir /usr/local/redis## 解压redis
tar -zxvf redis-3.2.7.tar## 重命名安装目录
mv redis-3.2.7.tar /opt/redis## 进入安装目录
cd /opt/redis## 编译安装redis
make PREFIX=/usr/local/redis install
安装完成后,进入redis的目录下会有一个bin目录,目录中有redis的脚本:
## redis的脚本
redis-benchmark redis-check-aof redis-check-rdb redis-cli redis-sentinel redis-server
4. 将redis启动脚本
## 拷贝redis的启动脚本到init.d目录
cp /opt/redis/utils/redis_init_script /etc/rc.d/init.d/redis## 编辑脚本
vi /etc/rc.d/init.d/redis
需要修改这个脚本,修改后的脚本如下:
#!/bin/sh
#chkconfig: 2345 80 90
#
# Simple Redis init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.REDISPORT=6379
EXEC=/usr/local/redis/bin/redis-server
CLIEXEC=/usr/local/redis/bin/redis-cliPIDFILE=/var/run/redis_${REDISPORT}.pid
CONF="/usr/local/redis/conf/${REDISPORT}.conf"case "$1" instart)if [ -f $PIDFILE ]thenecho "$PIDFILE exists, process is already running or crashed"elseecho "Starting Redis server..."$EXEC $CONF &fi;;stop)if [ ! -f $PIDFILE ]thenecho "$PIDFILE does not exist, process is not running"elsePID=$(cat $PIDFILE)echo "Stopping ..."$CLIEXEC -p $REDISPORT shutdownwhile [ -x /proc/${PID} ]doecho "Waiting for Redis to shutdown ..."sleep 1doneecho "Redis stopped"fi;;*)echo "Please use start or stop as first argument";;
esac
5. 将redis注册为服务
## 注册redis脚本为服务
chkconfig --add redis## 开启服务
systemctl start redis.service## 开启启动服务
systemctl enable redis.service
6. 设置防火墙
## 开放端口
firewall-cmd --zone=public --add-port=6379/tcp --permanent## 重启防火墙
firewall-cmd --reload
7. 修改redis的配置文件
## 创建配置文件的目录
mkdir /usr/local/redis/conf## 服务redis配置文件到这个目录
cp /opt/redis/redis.conf /usr/local/redis/conf/6379.conf## 编辑配置文件
vi /usr/local/redis/conf/6379.conf
将daemonize改为yes,并开放远程连接,修改bind为0.0.0.0。
8. 添加环境变量
## 编辑profile文件
vi /etc/profile## 加入redis环境变量
#redis env
export REDIS_HOME=/usr/local/redis
export PATH=$PATH:$REDIS_HOME/bin## 编译修改后的profile
source /etc/profile## 重启redis服务
systemctl restart redis.service
9. 通过redis-cli测试:
## 命令行输入
redis-cli## 如果成功连接redis会出现
127.0.0.1:6379>
10. 使用jedis连接
下载jedis的jar包:
<!-- redis --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.9.0</version></dependency>
编写代码连接redis:
package cn.net.bysoft.redis.test;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;import redis.clients.jedis.Jedis;public class RedisTest {private final Log log = LogFactory.getLog(RedisTest.class);@Testpublic void test() {String key = "hello";Jedis jedis = new Jedis("192.168.240.132", 6379);jedis.set(key, "world");String str = jedis.get(key);log.info("==>" + str);jedis.del(key);str = jedis.get(key);log.info("==>" + str);jedis.close();}}
运行上面的代码,成功连接的话,会输出:
2017-02-11 14:10:39,748 INFO [RedisTest.java:20] : ==>world
2017-02-11 14:10:39,753 INFO [RedisTest.java:24] : ==>null
11. 使用spring连接redis
下载jar包:
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.4.2</version>
</dependency>
连接池的配置文件:
<?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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- Jedis链接池配置 --><bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"><property name="testWhileIdle" value="true" /><property name="minEvictableIdleTimeMillis" value="60000" /><property name="timeBetweenEvictionRunsMillis" value="30000" /><property name="numTestsPerEvictionRun" value="-1" /><property name="maxTotal" value="8" /><property name="maxIdle" value="8" /><property name="minIdle" value="0" /></bean><bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool"><constructor-arg index="0" ref="jedisPoolConfig" /><constructor-arg index="1"><list><bean class="redis.clients.jedis.JedisShardInfo"><constructor-arg index="0" value="192.168.240.132" /><constructor-arg index="1" value="6379" type="int" /></bean></list></constructor-arg></bean>
</beans>
spring配置文件:
<?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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"default-autowire="byName" default-lazy-init="false"><!-- 采用注释的方式配置bean --><context:annotation-config /><!-- 配置要扫描的包 --><context:component-scan base-package="cn.net.bysoft.redis.test" /><!-- proxy-target-class默认"false",更改为"ture"使用CGLib动态代理 --><aop:aspectj-autoproxy proxy-target-class="true" /> <import resource="spring-redis.xml" />
</beans>
测试代码:
package cn.net.bysoft.redis.test;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/spring-context.xml" })
public class RedisSpringTest {private static final Log log = LogFactory.getLog(RedisSpringTest.class);@Autowiredprivate ShardedJedisPool shardedJedisPool;@Testpublic void test() {ShardedJedis jedis = shardedJedisPool.getResource();String key = "hello";String value = "";jedis.set(key, "world");value = jedis.get(key);log.info(key + "=" + value);jedis.del(key); // 删数据value = jedis.get(key); // 取数据log.info(key + "=" + value);}}
如果成功连接,会输出:
2017-02-11 14:19:56,776 INFO [AbstractTestContextBootstrapper.java:258] : Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
2017-02-11 14:19:56,793 INFO [AbstractTestContextBootstrapper.java:207] : Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
2017-02-11 14:19:56,796 INFO [AbstractTestContextBootstrapper.java:185] : Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@7ca48474, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@337d0578, org.springframework.test.context.support.DirtiesContextTestExecutionListener@59e84876, org.springframework.test.context.transaction.TransactionalTestExecutionListener@61a485d2, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@39fb3ab6]
2017-02-11 14:19:56,903 INFO [XmlBeanDefinitionReader.java:317] : Loading XML bean definitions from class path resource [spring/spring-context.xml]
2017-02-11 14:19:57,127 INFO [XmlBeanDefinitionReader.java:317] : Loading XML bean definitions from class path resource [spring/spring-redis.xml]
2017-02-11 14:19:57,160 INFO [AbstractApplicationContext.java:578] : Refreshing org.springframework.context.support.GenericApplicationContext@3532ec19: startup date [Sat Feb 11 14:19:57 CST 2017]; root of context hierarchy
2017-02-11 14:19:57,455 INFO [RedisSpringTest.java:31] : hello=world
2017-02-11 14:19:57,457 INFO [RedisSpringTest.java:35] : hello=null
2017-02-11 14:19:57,459 INFO [AbstractApplicationContext.java:960] : Closing org.springframework.context.support.GenericApplicationContext@3532ec19: startup date [Sat Feb 11 14:19:57 CST 2017]; root of context hierarchy