redis的使用

来源:互联网 发布:端口数据监听工具 编辑:程序博客网 时间:2024/06/13 06:23

Redis 安装

Window 下安装

下载地址:https://github.com/MSOpenTech/redis/releases。

下载好后,就要启动redis服务器了,我存在了这里

1.cmd打开dos命令,进入D:\redis-2.4.5-win32-win64\64bit里,然后执行启动服务器:redis-server redis.conf

2.server启动后再打开一个dos启动client   输入命令启动客户端:redis-cli.exe -h 127.0.0.1 -p 6379

3.添加redis的客户端java开发工具,首先需要再项目的pom.xml文件中添加相应的依赖

<!-- redis客户端:jedis -->
         <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.3</version>
         </dependency>

4.其中在往redis存储数据和取出数据时,需要序列化和反序列化,为了提升效率,我们没有用javaJDK自带的序列化,自己自定义了protostuff序列化,相应的依赖也一并加入

<!-- protostuff序列化依赖 -->
          <dependency>
               <groupId>com.dyuproject.protostuff</groupId>
               <artifactId>protostuff-core</artifactId>
               <version>1.0.8</version>
          </dependency>
          <dependency>
               <groupId>com.dyuproject.protostuff</groupId>
               <artifactId>protostuff-runtime</artifactId>
               <version>1.0.8</version>
          </dependency>


5.  创建redisdao类

package org.seckill.dao;
import org.seckill.entity.Seckill;
import org.slf4j.LoggerFactory;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import ch.qos.logback.classic.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class RedisDao {
 private final Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());
 private final JedisPool jedisPool;
 public RedisDao(String ip, int port) {
  jedisPool = new JedisPool(ip, port);
 }
 private RuntimeSchema<Seckill> schema = RuntimeSchema.createFrom(Seckill.class);
 private RuntimeSchema<Long> schema1 = RuntimeSchema.createFrom(Long.class);
 public Seckill getSeckill(long seckillId) {
  // redis操作逻辑
  try {
   Jedis jedis = jedisPool.getResource();
   try {
    String key = "seckill:" + seckillId;
    // 并没有实现内部序列化操作
    // get->byte[]->反序列化->Object(Seckill)
    // 采用自定义序列化
    // protostuff:poji.
    byte[] bytes = jedis.get(key.getBytes());
    // 缓存重新取到
    if (bytes != null) {
     // 空对象
     Seckill seckill = schema.newMessage();
     ProtostuffIOUtil.mergeFrom(bytes, seckill, schema);
     // seckill被反序列化
     return seckill;
    }
   } finally {
    jedis.close();
   }
  } catch (Exception e) {
   logger.error(e.getMessage(), e);
  }
  return null;
 }
 public String putSeckill(Seckill seckill) {
  // set object(Seckill) ->序列化->byte[]
  try {
   Jedis jedis = jedisPool.getResource();
   try {
    String key = "seckill:" + seckill.getSeckillId();
    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(e.getMessage(), e);
  }
  return null;
 }
 
 //向redis根据seckillId存放剩余存量
 public String putCapacity(long seckillId,long capacity){
  try {
   Jedis jedis = jedisPool.getResource();
   try {
    String key = "capacity:" + seckillId;
    byte[] bytes=ProtostuffIOUtil.toByteArray(capacity, schema1,
      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(e.getMessage(), e);
  }
  return null;
 }
 
 
 public long getCapacity(long seckillId){
  try {
   Jedis jedis = jedisPool.getResource();
   try{
    String key = "capacity:" + seckillId;
    // 并没有实现内部序列化操作
    // get->byte[]->反序列化->Object(Seckill)
    // 采用自定义序列化
    // protostuff:poji.
    byte[] bytes = jedis.get(key.getBytes());
    // 缓存重新取到
    if (bytes != null) {
     // 空对象
     Long capacity = schema1.newMessage();
     ProtostuffIOUtil.mergeFrom(bytes, capacity, schema1);
     // seckill被反序列化
     return capacity;
    }
    
   } finally {
    jedis.close();
   }
  } catch (Exception e) {
   logger.error(e.getMessage(), e);
  }  
  return 0;
 }
}

6.测试类来测试

package org.seckill.dao;
import java.util.Date;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.seckill.dto.Exposer;
import org.seckill.entity.Seckill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/*
 * 配置spring和junit4整合,junit启动时加载springIOC容器
 * */
@RunWith(SpringJUnit4ClassRunner.class)
// 告诉junit spring配置文件
@ContextConfiguration({ "classpath:spring/spring-dao.xml" })
public class RedisDaotest {
   // 注入Dao实现类依赖
    @Resource
    private SeckillDao seckillDao;
   
    @Autowired
    private RedisDao redisDao;
   
    @Test
    public void testCapacity(){
     long seckillId=1000;
     long capacity=seckillDao.capacityById(seckillId);
     System.out.println("capacity:"+capacity);
//     String Stringresult=redisDao.putCapacity(seckillId, capacity);
//     System.out.println(Stringresult);
//     long result=redisDao.getCapacity(seckillId);
//     System.out.println("redis获取到capcity:"+result);
    }
   
   
    @Test
    public void testSeckill(){
     long seckillId=1000;
     Seckill seckill=redisDao.getSeckill(seckillId);
//     if(seckill==null){
       seckill=seckillDao.queryById(seckillId);
//      if(seckill!=null){
      String result=redisDao.putSeckill(seckill);
      
      System.out.println("result:"+result);
         seckill=redisDao.getSeckill(seckillId);
         System.out.println(seckill);
//      }
//     }else{
//     System.out.println(seckill);
//    }
     Date startTime = seckill.getStartTime();
        Date endTime = seckill.getEndTime();
     Date nowTime = new Date();
        if (nowTime.getTime() < startTime.getTime() || nowTime.getTime() > endTime.getTime()) {
           System.out.println("秒杀未开启");
        }else{
         System.out.println("秒杀开启了");
        }
        seckill=redisDao.getSeckill(seckillId);
     System.out.println(seckill);
    }
}

注意:这个项目是SSM框架下的


原创粉丝点击