redis(单机版)安装部署以及java调用工具类

安装部署步骤

1. 准备工作

  将下载好的redis-3.2.2.tar.gz上传到linux服务器 /lamp,进行解压解压

    tar -zxvf redis-3.2.2.tar.gz

  网址:http://download.redis.io/releases/redis-3.2.2.tar.gz

2. 进行编译

    cd redis-3.2.2

    make

  make这一步可能会报错,如果报错,可以尝试使用如下命令来编译:

    make MALLOC=libc

  ( 注意:make指令是需要linux下安装gcc的 如果没有gcc可以尝试安装

yum -y install gcc )

编译好的二进制文件会放到src/目录下,可以看到有redis-server和redis-cli,这是redis的服务端和客户端,我们到时候可以直接运行这两个文件即可启动服务端和客户端

3. 创建目录移动文件、便于管理:

    mkdir –p /usr/local/redis/bin 放命令

    mkdir –p /usr/local/redis/etc放配置文件

然后将上面src目录下的命令和配置文件分别移动到对应的目录

     mv /lamp/redis-3.2.2/redis.conf /usr/local/redis/etc

     cd /lamp/redis-3.2.2/src

     mv mkreleasdhdr.sh redis-benchmark redis-check-aof redis-check-dump redis-cli  redis-server /usr/local/redis/bin

4. 启动redis服务:

进入到/usr/local/redis/bin目录下,执行

     ./redis-server /usr/local/redis/etc/redis.conf

  这是根据配置文件redis.conf来启动redis服务,但是默认是前台启动的,会占用我的session,如果想要后台启动redis,还需要修改一下redis.conf的配置,打开该配置文件:

      vi /usr/local/redis/etc/redis.conf

然后将daemonize no改为yes,然后再启动一下redis服务就可以后台启动了,然后我们可以查看一下是否启动成功:

      ps -ef | grep redis 查看是否启动成功

      netstat -tunpl | grep 6379 查看该端口有没有占用

 5. 启动redis客户端:(在redis.conf 中增加 requirepass = ylx (密码))

redis客户端命令也在bin目录下,是redis-cli文件,运行一下即可启动redis客户端:

      ./redis-cli -a ylx

随便往里面插入一个name为test测试一下,可以正常获取,说明客户端没有问题。

      set name test

      get name

退出客户端的话直接quit即可。

6. 关闭redis服务:

        关闭redis服务的话直接使用如下命令即可:

            pkill redis-server

java调用工具类

   配置文件   application.properties

#redis
redis.ip=192.168.203.13
redis.auth=ylx
redis.port=6379
redis.timeout=10000
redis.MaxTotal=200
redis.MaxIdle=200
redis.MinIdle=0
redis.MaxWaitMillis=-1
redis_list_len=100000


1. 加载redis配置文件

package com.eversec.pierce.redis;

import com.eversec.pierce.util.PropertiesLoader;

public class RedisConfig {

/**
* 加载redis配置文件
*/
private static PropertiesLoader propertiesLoader = null;
static{
propertiesLoader = new PropertiesLoader("application.properties");
String active=propertiesLoader.getProperty("spring.profiles.active");
propertiesLoader = new PropertiesLoader("application-"+active+".properties");
}

public static String getRedisConfig(String key){
return propertiesLoader.getProperty(key);
}
}

2. 维护redis连接池资源

package com.eversec.pierce.redis;

import java.io.Serializable;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
* 维护redis连接池资源
* @author root
*
*/
public class RedisResources {
private static final Logger logger = LoggerFactory.getLogger(RedisResources.class);
private static String IP = RedisConfig.getRedisConfig("redis.ip");// 连接地址
private static String AUTH = RedisConfig.getRedisConfig("redis.auth");// 认证信息
private static int PORT = Integer.parseInt(RedisConfig.getRedisConfig("redis.port"));
private static int TIMEOUT = Integer.parseInt(RedisConfig.getRedisConfig("redis.timeout"));// 超时时间
private static int MaxTotal = Integer.parseInt(RedisConfig.getRedisConfig("redis.MaxTotal"));
private static int MaxIdle = Integer.parseInt(RedisConfig.getRedisConfig("redis.MaxIdle"));
private static int MinIdle = Integer.parseInt(RedisConfig.getRedisConfig("redis.MinIdle"));
private static int MaxWaitMillis = Integer.parseInt(RedisConfig.getRedisConfig("redis.MaxWaitMillis"));

private static JedisPool jedisPool = null;
/**
* 加载redis连接池
*/
static {
init();
}
private static void init(){
JedisPoolConfig config = new JedisPoolConfig();
//config.setMaxWaitMillis(MAX_WAIT);
//config.setMaxTotal(MAX_ACTIVE);
//config.setMinIdle(MIN_IDLE);
//config.setTestOnBorrow(TEST_ON_BORROW);
//-------------------------------------------------

config.setMaxTotal(MaxTotal);
config.setMaxIdle(MaxIdle);
config.setMinIdle(MinIdle);//设置最小空闲数
config.setMaxWaitMillis(MaxWaitMillis);
//config.setTestOnBorrow(TestOnBorrow);
//config.setTestOnReturn(TestOnReturn);
//Idle时进行连接扫描
//config.setTestWhileIdle(TestWhileIdle);
//表示idle object evitor两次扫描之间要sleep的毫秒数
//config.setTimeBetweenEvictionRunsMillis(TimeBetweenEvictionRunsMillis);
//表示idle object evitor每次扫描的最多的对象数
//config.setNumTestsPerEvictionRun(NumTestsPerEvictionRun);
//表示一个对象至少停留在idle状态的最短时间,然后才能被idle object evitor扫描并驱逐;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
//config.setMinEvictableIdleTimeMillis(MinEvictableIdleTimeMillis);

jedisPool = new JedisPool(config,IP,PORT,TIMEOUT,AUTH);
}

/**
* 从连接池里获取redis连接
* @return
*/
public static Jedis getResources(){
int i=0;
Jedis jedis=null;
while(true){
try{
jedis=jedisPool.getResource();
}catch(Exception e){
init();
jedis=jedisPool.getResource();
logger.error("Redis连接失败,第"+i+"次连接");
}
if(jedis != null){
return jedis;
}
}
}
}


3. redis使用工具类

package com.eversec.pierce.redis;

import java.io.Serializable;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eversec.pierce.config.Global;

import redis.clients.jedis.Jedis;


/**
* redis使用工具类
* @author root
*
*/
public class RedisTemplate<T extends Serializable> {
private static final Logger logger = LoggerFactory.getLogger(RedisTemplate.class);

/**
* 保存字符串
* @param key
* @param value
*/
public void setStr(String key,String value)throws Exception{
Jedis jedis = null;
try{
jedis = RedisResources.getResources();
jedis.set(key, value);
}catch(Exception e){
logger.error("Redis工具类异常",e);
throw new Exception(e);
}finally{
if (jedis != null) {
jedis.close();
}
}

}

/**
* 获取字符串值
* @param key
* @return
*/
public String getStr(String key) throws Exception{
Jedis jedis = null;
String value=null;
try{
jedis = RedisResources.getResources();
value = jedis.get(key);
}catch(Exception e){
logger.error("Redis工具类异常",e);
throw new Exception(e);
}finally{
if (jedis != null) {
jedis.close();
}
}
return value;
}

/**
* 保存List
* @param key
* @param t
*/
public <T extends Serializable > long setList(String key,String value) throws Exception{
Jedis jedis = null;
try {
jedis = RedisResources.getResources();
long lag=jedis.rpush(key, value);
return lag;
} catch (Exception e) {
logger.error("Redis工具类异常",e);
throw new Exception(e);
}finally{
if (jedis != null) {
jedis.close();
}
}
}

/**
* 获取List
*/

public <T extends Serializable> List<T> getList(String key)throws Exception{
Jedis jedis = null;
List<T> t = null;
try{
jedis = RedisResources.getResources();
int len_end = Integer.parseInt(Global.getConfig("redis_list_len"));
t=(List<T>) jedis.lrange(key,0,len_end);//返回List集合
}catch(Exception e){
logger.error("Redis工具类异常",e);
throw new Exception(e);
}finally{
if (jedis != null) {
jedis.close();
}
}
return t;
}




/**
* 清空List
*/

public <T extends Serializable> void delList(String key)throws Exception{
Jedis jedis = null;
try{
jedis = RedisResources.getResources();
jedis.del(key);
}catch(Exception e){
logger.error("Redis工具类异常",e);
throw new Exception(e);
}finally{
if (jedis != null) {
jedis.close();
}
}
}

/**
* 移除List中的元素
*/

public <T extends Serializable> void removeList(String key,Long index) throws Exception{
Jedis jedis = null;
try{
jedis = RedisResources.getResources();
//ltrim: ltrim mylist 1 -1 //保留mylist中 1到末尾的值,即删除第一个值。
jedis.ltrim(key, index, -1);
}catch(Exception e){
logger.error("Redis工具类异常",e);
throw new Exception(e);
}finally{
if (jedis != null) {
jedis.close();
}
}
}

}



以上是本人自己总结,并且在项目总实际运用操作的。新手一枚,不喜勿喷!(接下来的文章中会有 redis集群版的安装部署以及java调用工具类)

猜你喜欢

转载自www.cnblogs.com/yanlixiong/p/9548432.html
今日推荐