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));
    }
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章