java redis基础配置及简单操作

1、maven项目添加相关依赖,spring相关依赖也要一并添加进去!

         <!-- redis -->
         <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.6.6.RELEASE</version>
        </dependency>

2.配置spring-redis.xml文件

首先web.xml文件加载spring-redis.xml

spring-redis具体配置:

<?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:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">


    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="2000" />
        <property name="maxTotal" value="20000" />
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="numTestsPerEvictionRun" value="3" />
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <property name="maxWaitMillis" value="20000" />
        <property name="testOnBorrow" value="false" />
    </bean>

      <!-- redis服务器中心 -->
    <bean id="redisConnectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="poolConfig" ref="poolConfig" />
        <property name="port" value="6379" />
        <property name="hostName" value="192.168.17.129" />
        <property name="password" value="" />
        <property name="database" value="0"></property>
    </bean>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="redisConnectionFactory" />
        <!-- 如果不配置Serializer,那么存储的时候只能使用String -->
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        </property>
    </bean>

</beans>

3.使用两种方法测试方法简单实用redis

一、RedisTempate使用spring管理(注意要添加spring-test依赖)

package project.dao;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import elasticsearch.Student;

import java.util.*;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-redis.xml"})
public class RedisTempate {
    /**
     * 使用object泛型插入的数据都是以object对象插入到库里的
     */
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    public void insertEntity() {
        //System.out.println(redisTemplate);
        Student student = new Student();
        student.setName("xiaoming");
        student.setAge(12);
        redisTemplate.opsForValue().set(student.getName(),student);
    }
    @Test
    public void getEntity() {
        Student student =(Student) redisTemplate.opsForValue().get("xiaoming");
        System.out.println(student);
    }
    @Test
    public void insertString() {
        redisTemplate.opsForValue().set("xiaojun", "13");
    }
    
    @Test
    public void getString() {
        String values=(String) redisTemplate.opsForValue().get("xiaojun");
        System.out.println(values);
    }
    /**
     * 增加过期时间
     */
    @Test
    public void insertBytime() {
        Student student = new Student();
        student.setName("测试");
        student.setAge(125);
        redisTemplate.opsForValue().set(student.getName(),student); //插入数据
        redisTemplate.expire(student.getName(), 5, TimeUnit.MINUTES); //设置过期时间
    }
    
    @Test
    public void insertList() {
        List<String> list=new ArrayList<String>();
        list.add("aa");
        list.add("da");
        list.add("ta");
        redisTemplate.opsForValue().set("testlist",list); //插入数据
    }
    @Test
    public void getList() {
        List<String> list=(List<String>) redisTemplate.opsForValue().get("testlist");
        System.out.println(list);
    }
    @Test
    public void insertMap() {
        Map<String ,Student> map=new HashMap<String ,Student>();
        Student student = new Student();
        student.setName("测试");
        student.setAge(125);
        Student student1 = new Student();
        student1.setName("测试1");
        student1.setAge(1251);
        map.put(student.getName(), student);
        map.put(student1.getName(), student1);
        redisTemplate.opsForValue().set("map1", map);
    }
    @Test
    public void getMap() {
        Map<String ,Student> map=(Map<String, Student>) redisTemplate.opsForValue().get("map1");
        System.out.println(map);
    }
    /**
     * 删除任何类型List,Map,String...
     */
    @Test
    public void delete() {
        redisTemplate.delete("age");
    }
    /**
     * 判断时候存在某个对象
     */
    @Test
    public void exists() {
        Boolean flag=redisTemplate.hasKey("zset1");
        System.out.print(flag);
    }
 
}

二、使用Jedis操作redis,缺点使用后要手动关闭jedis连接

package project.dao;

import java.util.*;

import org.junit.Test;
import redis.clients.jedis.Jedis;

public class TestRedis {    
    
    
    // 第一步:创建一个Jedis对象。需要指定服务端的ip及端口。
    Jedis jedis = new Jedis("192.168.17.129", 6379);
    /**
     * redis操作字符串
     * @throws Exception
     */
    @Test
    public void testString() throws Exception {
        
        // 第二步:使用Jedis对象操作数据库,每个redis命令对应一个方法。
        jedis.set("name", "xiangjun");
        String result = jedis.get("name");
        // 第三步:打印结果。
        System.out.println(result);
        
           // 拼接字符串
        jedis.append("name", ".com");
        System.out.println(jedis.get("name"));

        // 删除数据
        jedis.del("name");
        System.out.println(jedis.get("name"));

        // 设置多个键值对
        jedis.mset("name", "xiangjun", "age", "23", "qq", "47670002");
        jedis.incr("age"); // 加1操作
        System.out.println(jedis.get("name") + "-" + jedis.get("age") + "-" + jedis.get("qq"));

        // 第四步:关闭Jedis
        jedis.close();
    }    
     /**
     * redis操作map集合
     */
    @Test
    public void testMap() {
        // 添加数据
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "xiangjun");
        map.put("age", "22");
        map.put("qq", "5443343");
        jedis.hmset("user", map);
        // 取出user中的name,执行结果:[minxr]-->注意结果是一个泛型的List
        // 第一个参数是存入redis中map对象的key,后面跟的是放入map中的对象的key,后面的key可以跟多个,是可变
        List<String> rsmap = jedis.hmget("user", "name", "age", "qq");
        System.out.println(rsmap);

        // 删除map中的某个键值
        jedis.hdel("user", "age");
        System.out.println(jedis.hmget("user", "age")); // 因为删除了,所以返回的是null
        System.out.println(jedis.hlen("user")); // 返回key为user的键中存放的值的个数2
        System.out.println(jedis.exists("user"));// 是否存在key为user的记录 返回true
        System.out.println(jedis.hkeys("user"));// 返回map对象中的所有key
        System.out.println(jedis.hvals("user"));// 返回map对象中的所有value

        Iterator<String> iter = jedis.hkeys("user").iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            System.out.println(key + ":" + jedis.hmget("user", key));
        }
        // 第四步:关闭Jedis
        jedis.close();
    }
    /**
     * redis操作list集合
     */
    @Test
    public void testList() {
        // 开始前,先移除所有的内容
        jedis.del("java framework");
        System.out.println(jedis.lrange("java framework", 0, -1));
        // 先向key java framework中存放三条数据
        jedis.lpush("java framework", "spring");
        jedis.lpush("java framework", "struts");
        jedis.lpush("java framework", "hibernate");
        // 再取出所有数据jedis.lrange是按范围取出,
        // 第一个是key,第二个是起始位置,第三个是结束位置,jedis.llen获取长度 -1表示取得所有
        System.out.println(jedis.lrange("java framework", 0, -1));

        jedis.del("java framework");
        jedis.rpush("java framework", "spring");
        jedis.rpush("java framework", "struts");
        jedis.rpush("java framework", "hibernate");
        System.out.println(jedis.lrange("java framework", 0, -1));
        // 第四步:关闭Jedis
        jedis.close();
    }
     /**
     * redis操作set集合
     */
    @Test
    public void testSet() {
        //切换redis数据库(redis默认有16个,每个数据库相互独立)
        jedis.select(1);
        // 添加
        jedis.sadd("user1", "liuling");
        jedis.sadd("user1", "xinxin");
        jedis.sadd("user1", "ling");
        jedis.sadd("user1", "zhangxinxin");
        jedis.sadd("user1", "who");
        // 移除noname
        jedis.srem("user1", "who");
        System.out.println(jedis.smembers("user1"));// 获取所有加入的value
        System.out.println(jedis.sismember("user1", "who"));// 判断 who
                                                            // 是否是user集合的元素
        System.out.println(jedis.srandmember("user1"));
        System.out.println(jedis.scard("user1"));// 返回集合的元素个数
        // 第四步:关闭Jedis
         jedis.close();
    }
    /**
     * redis排序
     */
    @Test
    public void testSort() {
        // jedis 排序
        // 注意,此处的rpush和lpush是List的操作。是一个双向链表(但从表现来看的)
        jedis.del("a");// 先清除数据,再加入数据进行测试
        jedis.rpush("a", "1");
        jedis.lpush("a", "6");
        jedis.lpush("a", "3");
        jedis.lpush("a", "9");
        System.out.println(jedis.lrange("a", 0, -1));// [9, 3, 6, 1]
        System.out.println(jedis.sort("a")); // [1, 3, 6, 9] //输入排序后结果
        System.out.println(jedis.lrange("a", 0, -1));
    }
}
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值