安装路径 /webapp/redis/redis-3.2.3 #启动redis /webapp/redis/redis-3.2.3/src/redis-server & #关闭redis /webapp/redis/redis-3.2.3/src/redis-cli shutdown
1、安装$ wget http://download.redis.io/releases/redis-3.2.3.tar.gz$ tar xzf redis-3.2.3.tar.gz$ cd redis-3.2.3$ make MALLOC=libc#启动redissrc/redis-server &#关闭redissrc/redis-cli shutdown$ src/redis-cli127.0.0.1:6379> set foo barOK127.0.0.1:6379> get foo"bar"$
2、java中的使用
使用Java操作Redis需要jedis-2.1.0.jar,下载地址:
如果需要使用Redis连接池的话,还需commons-pool-1.5.4.jar,下载地址:
//连接服务器的 Redis 服务Jedis jedis = new Jedis("192.168.248.129", 6379);//权限认证jedis.auth("123456");
3、报错解决
a、绑定的ip修改,修改redis-3.2.3文件夹下的redis.conf文件
# bind 127.0.0.1 注掉绑定的本机ip地址
b、设置密码
# redis-cli
# config set requirepass 123456
NOAUTH Authentication required.
提示没有权限访问的时候
输入 auth "yourpassword" 即可连接 连接redis之前应该查看服务防火墙是否关闭,或者开启redis默认的端口 序列化的应用
/** Copyright (c) 2016 Sohu TV. All rights reserved.*/package com.sohu.dao.redis;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import com.dyuproject.protostuff.LinkedBuffer;import com.dyuproject.protostuff.ProtostuffIOUtil;import com.dyuproject.protostuff.runtime.RuntimeSchema;import com.sohu.model.Seckill;/** ** Description: *
* @author jfw * @version 1.0 * @Date 2016年2月14日下午2:51:48 */public class RedisDao { private final JedisPool jedisPool; private final RuntimeSchemaschema=RuntimeSchema.createFrom(Seckill.class); private final Logger logger=LoggerFactory.getLogger(this.getClass()); public RedisDao(String ip,int port){ jedisPool=new JedisPool(ip,port); } public Seckill getSeckill(long seckillId){ try { Jedis jedis=jedisPool.getResource(); jedis.auth("123456"); try { String key="seckill:"+seckillId; byte[] bytes=jedis.get(key.getBytes()); if(bytes!=null){ Seckill seckill=schema.newMessage(); ProtostuffIOUtil.mergeFrom(bytes, seckill, schema); return seckill; } }finally{ jedis.close(); } } catch (Exception e) { logger.error("{seckillId}"+seckillId+e.getMessage(),e); } return null; } public String putSeckill(Seckill seckill){ try { Jedis jedis=jedisPool.getResource(); jedis.auth("123456"); try { String key="seckill:"+seckill.getId(); byte[] bytes=ProtostuffIOUtil.toByteArray(seckill, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE)); int timeout=60*60; String result=jedis.setex(key.getBytes(),timeout, bytes); return result; }finally{ jedis.close(); } } catch (Exception e) { logger.error("{seckill}"+seckill+e.getMessage(),e); } return null; }}
spring.xml配置
com.dyuproject.protostuff protostuff-core 1.0.8 com.dyuproject.protostuff protostuff-runtime 1.0.8 redis.clients jedis 2.7.2