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
?