redis简介及其基本操作,java访问redis

Redis

  • Redis是采用C语言编写,内存数据存储。
  • Redis读写速度异常快速,适合做应用缓存
  • Redis支持字符串、哈希、列表、集合、有序集合结构存储
  • Redis支持持久化操作(RDB和AOF机制)
  • Redis可以和Java、PHP、Python等语言结合访问

Redis操作命令

字符串操作(string)

  • set key value //设置一组key value
  • get key //获取value值
  • mset key value key value //设置多组key value
  • strlen key //查看value字符数量
  • incr key //将value值加1
  • incrby key n //将value值加n
  • decr key //将value值减1
  • decrby key n //将value值减n
  • append key value //字符串拼接

key操作

  • keys * //查看所有key
  • del key //删除key
  • type key //查看value类型
  • expire key n //指定失效时间(秒)

哈希操作(hash)

  • hset key field value //设置一组字段名和字段值
  • hmset key field1 value1 field2 value2... //设置多组字段名和字段值
  • hget key field //获取字段值
  • hmget key field1 field2 //获取多个字段值
  • hkeys key //查看哈希包含的字段名
  • hlen key //查看哈希包含的字段数量
  • hdel key field //删除哈希中的某个字段

列表操作(list)

  • lpush key value //向列表头部插入一个元素
  • rpush key value //向列表尾部插入一个元素
  • llen key //列表元素数量
  • lrange key 0 -1 //获取所有元素
  • lpop //弹出列表头部元素

集合操作

  • sadd key member //添加元素
  • srem key member //删除元素
  • smembers key //返回所有元素
  • scard key //返回集合元素数量
  • srandmember key n //随机返回n个
  • sunion key1 key2 //key1并key2
  • sinter key1 key2 //key1交key2
  • sdiff key1 key2 //key1差key2

有序集合操作

  • zadd key score member //添加元素
  • zcard key //集合元素数量
  • zrange key 0 -1 //由小到大顺序查看所有元素
  • zrevrange key 0 -1 //由大到小顺序查看所有元素
  • zcount key min max //按分数统计元素数量
  • zrem key memeber //删除元素

Java访问Redis

基于jedis.jar访问

@Test
public void test1(){
    Jedis jedis = new Jedis("localhost", 6379);
    System.out.println(jedis.ping());
    Set<String> keys = jedis.keys("*");//keys *
    for(String key:keys){
        System.out.println(key+":"+jedis.type(key));
    }
    jedis.close();
}

@Test
public void test2(){
    Jedis jedis = new Jedis("localhost", 6379);
    //取string
    String value1 = jedis.get("name");//get name
    System.out.println("name="+value1);
    //取hash
    String value2 = jedis.hget("dept10", "dname");//hget dept10 dname
    System.out.println("dname="+value2);
    //获取hash所有字段值
    Set<String> fields = jedis.hkeys("dept20");
    for(String f:fields){
        System.out.println(f+":"+jedis.hget("dept20", f));
    }
    jedis.close();
}

@Test
public void test3(){

    Map<String, String> data = new HashMap<>();
    data.put("no", "101");
    data.put("name", "tom");

    Jedis jedis = new Jedis("localhost", 6379);

    jedis.hmset("mymap1", data);//存入map
    Map<String,String> map = jedis.hgetAll("mymap1");//获取map
    System.out.println(map.get("no")+" "+map.get("name"));
    jedis.close();
}

@Test
public void test4(){
    Dept dept = new Dept();
    dept.setDeptno(10);
    dept.setDname("Java");
    dept.setLoc("北京");

    Jedis jedis = new Jedis("localhost", 6379);
    jedis.set("dept".getBytes(), SerializableUtil.objectToBytes(dept));
    jedis.close();

}

@Test
public void test5(){
    Jedis jedis = new Jedis("localhost", 6379);
    byte[] bytes = jedis.get("dept".getBytes());
    Dept dept = (Dept)SerializableUtil.bytesToObject(bytes);
    System.out.println(dept.getDeptno()+" "+dept.getDname()+" "+dept.getLoc());
    jedis.close();
}

SerializableUtil.java

public class SerializableUtil {

    public static Object bytesToObject(byte[] bytes){
        ByteArrayInputStream input = null;
        ObjectInputStream ois = null;
        try{
            input = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(input);
            Object obj = ois.readObject();//反序列化将字节数组转成Object
            return obj;
        }catch(Exception ex){
            ex.printStackTrace();
            return null;
        }finally{
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static byte[] objectToBytes(Object obj){
        ByteArrayOutputStream out = null;
        ObjectOutputStream oos = null;
        try{
            out = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(out);
            oos.writeObject(obj);//将obj序列化后写入out对象中
            byte[] bytes = out.toByteArray();
            return bytes;
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }finally{
            try {
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                oos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

基于SpringData-redis访问

  1. 引入spring-data-redis包、jedis、connection-pool包

  2. 在Spring配置文件定义RedisTemplate、JedisConnectionFactory组件

    <bean id="redisConnectionFactory" 
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="localhost">
        </property>
        <property name="port" value="6379"></property>
    </bean>
    
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="redisConnectionFactory">
        </property>
    </bean>
    
  3. 注入RedisTemplate测试

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={"classpath:applicationContext.xml"})
    public class TestRedisTemplate {
    
        @Autowired
        private RedisTemplate<Object,Object> redisTemplate;
    
        @Test
        public void test1(){
            redisTemplate.opsForValue().set("name", "XDL");
            String value = (String)redisTemplate.opsForValue().get("name");
            System.out.println(value);
    
        }
    
        @Test
        public void test2(){
            Dept dept = new Dept();
            dept.setDeptno(20);
            dept.setDname("XDL");
            dept.setLoc("北京");
    
            redisTemplate.opsForValue().set("dept", dept);
    
            Dept d = (Dept)redisTemplate.opsForValue().get("dept");
            System.out.println(d.getDeptno()+" "+d.getDname()+" "+d.getLoc());
        }
    
    }
    

Redis缓存使用

@Resource
private RedisTemplate<Object, Object> redisTemplate;

@RequestMapping(value="/dept/get",method=RequestMethod.GET)
public Dept loadDept(@RequestParam("no")int id){
    //查找Redis缓存,有返回
    Dept dept = (Dept)redisTemplate.opsForValue().get("dept:"+id);
    //Redis没有,调用deptDao查询数据库,并将结果放入缓存
    if(dept == null){
        System.out.println("从数据库查询加载数据");
        dept = deptDao.findById(id);
        redisTemplate.opsForValue().set("dept:"+id, dept);
    }else{
        System.out.println("从Redis缓存查询加载数据");
    }
    return dept;
}
posted @ 2019-03-14 18:53  Hero丶小卡  阅读(533)  评论(0编辑  收藏  举报