1. 程式人生 > >Redis的基本使用(基於maven和spring)

Redis的基本使用(基於maven和spring)

opera redist scac bottom 合成 創建 ann private public

  • 使用redis基本測試

maven導包

      <dependency>
          <groupId>redis.clients</groupId>
          <artifactId>jedis</artifactId>
          <version>2.9.0</version>
      </dependency>

基本連接

public static void main(String[] args) {
        // 連接本地的 Redis 服務
        Jedis jedis = new
Jedis("localhost"); System.out.println("連接成功"); // 查看服務是否運行 System.out.println("服務正在運行: " + jedis.ping()); }

存入string類型的值

public static void main(String[] args) {
        // 連接本地的 Redis 服務
        Jedis jedis = new Jedis("localhost");
        //使用字符串string存值
        jedis.set("城市", "南京");
    }

在圖形化redis客戶端可以看到,存值成功

技術分享

string類型取值

Jedis jedis = new Jedis("localhost");
        String city = jedis.get("城市");

存入list集合類型的值

public static void main(String[] args) {
        // 連接本地的 Redis 服務
        Jedis jedis = new Jedis("localhost");
        //使用字符串list存值
        jedis.lpush("城市", "南京");
        jedis.lpush(
"城市", "上海"); jedis.lpush("城市", "蘇州"); jedis.lpush("城市", "北京"); jedis.lpush("城市", "南通"); }

圖形化界面展示效果

技術分享

list集合取值

public static void main(String[] args) {
        // 連接本地的 Redis 服務
        Jedis jedis = new Jedis("localhost");
        //list集合取值,這裏註意的是,100的位置是結束的角標,如果大了沒事,小了的話就會缺
        List<String> arr = jedis.lrange("城市", 0, 100);
        System.out.println(arr.size());
        for (String string : arr) {
            System.out.println(string);
        }
    }

存入Map的值

map類型存值又叫Redis hash ,是一個string類型的field和value的映射表

public static void main(String[] args) {
        //連接本地的jedis服務器
        Jedis jedis=new Jedis("localhost");
        
        //Redis hash 是一個string類型的field和value的映射表,hash特別適合用於存儲對象。
        //這裏要求的是map必須是key和value都是string類型的
        Map<String, String> map=new HashMap<>();
        map.put("name", "小明");
        map.put("age", "13");
        map.put("sex", "男");
        map.put("height", "174");
        
        //調用jedis的hmset(存入hash map)的方法將map的鍵值對存進去
        jedis.hmset("people", map);
    }

圖形化客戶端界面顯示為:

技術分享

map取值

public static void main(String[] args) {
        //連接本地的jedis服務器
        Jedis jedis=new Jedis("localhost");
        
        //新建一個string類型的數組,用於存當時存入redis的map的key值
        String[] arr=new String[4];
        arr[0]="name";
        arr[1]="age";
        arr[2]="sex";
        arr[3]="height";
        //利用jedis的hmget方法,從數據庫中依次取出對應的map的key值
        List<String> list = jedis.hmget("people",arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.println("存入鍵值對為:"+arr[i]+"--"+list.get(i));
        }
        
    }

結果為:

存入鍵值對為:name--小明
存入鍵值對為:age--13
存入鍵值對為:sex--男
存入鍵值對為:height--174

存入Set的值

Redis的Set是string類型的無序集合。集合成員是唯一的,這就意味著集合中不能出現重復的數據。

存入代碼:

public static void main(String[] args) {
        //連接本地的jedis服務器
        Jedis jedis=new Jedis("localhost");
        
        //使用list存入數據
        List<String> list=new ArrayList<>();
        list.add("北京");
        list.add("南京");
        list.add("上海");
        list.add("北京");
        list.add("北京");
        list.add("上海");
        list.add("蘇州");
        list.add("南京");
        //打印源數據
        System.out.println("源數據為"+list);
        
        //因為jedis的sadd的方法,存入的是一個數組對象或者多數據,所有將集合對象轉換成數組對象
        String[] arr=new String[list.size()];
        for (int i = 0; i < arr.length; i++) {
            arr[i]=list.get(i);
        }
        //調用sadd方法存入數據庫
        jedis.sadd("city", arr);
        
    }

原來數據為:

源數據為[北京, 南京, 上海, 北京, 北京, 上海, 蘇州, 南京]

redis數據庫圖形化客戶端顯示

技術分享

可見,存入後,是把數據去重之後存儲的.

set數據的取出

public static void main(String[] args) {
        //連接本地的jedis服務器
        Jedis jedis=new Jedis("localhost");
        
        //調用jedis的smembers方法,獲取所有的set集合
        Set<String> smembers = jedis.smembers("city");
        
        System.out.println(smembers);
    }

控制臺結果為:

[北京, 上海, 南京, 蘇州]

存入sortset的值

Redis 有序集合和集合一樣也是string類型元素的集合,且不允許重復的成員。

存入代碼:

public static void main(String[] args) {
        //連接本地的jedis服務器
        Jedis jedis=new Jedis("localhost");
        
        Map<String, Double> map=new HashMap<>();
        map.put("北京", 1.0);
        map.put("北京", 2.0);
        map.put("南京", 3.0);
        map.put("上海", 4.0);
        map.put("上海", 5.0);
        map.put("南京", 6.0);
        
        //調用jedis的zadd方法存入
        jedis.zadd("city", map);
    }

圖形化客戶端界面:

技術分享

南京在放入map時候,是在上海之前,可是最後score卻取的是後面的一個.可見,如果有重復的數據產生的話,去重是將前面序號的重復去掉

取出代碼:

public static void main(String[] args) {
        //連接本地的jedis服務器
        Jedis jedis=new Jedis("localhost");
        
        //索引在0,到10之間的,分數由高到底的取出所有的集合
        Set<String> zrevrange = jedis.zrevrange("city", 0, 10);
        System.out.println(zrevrange);
        
    }

控制臺輸出:

[南京, 上海, 北京]

  • 使用redis的基於spring測試

使用spring整合

applicationContext.xml中配置

名稱空間:

xmlns:cache="http://www.springframework.org/schema/cache"    
    http://www.springframework.org/schema/cache
    http://www.springframework.org/schema/cache/spring-cache.xsd">

配置文件:

<!-- spring管理redis緩存管理器 -->
    <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg index="0" ref="redisTemplate" />
    </bean>

    <cache:annotation-driven cache-manager="redisCacheManager" />

    <!-- jedis 連接池配置 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="300" />
        <property name="maxWaitMillis" value="3000" />
        <property name="testOnBorrow" value="true" />
    </bean>

    <!-- redis的連接工廠 -->
    <bean id="connectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:host-name="localhost" p:port="6379" p:pool-config-ref="poolConfig"
        p:database="0" />

    <!-- spring data 提供 redis模板  -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="keySerializer">
            <bean
                class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean
                class="org.springframework.data.redis.serializer.StringRedisSerializer">
            </bean>
        </property>
    </bean>

在需要使用的service類中,使用註解

    //自動註入redis模板
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

使用spring整合string類型的值

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    @Test
    public void Test01(){
        //通過模板,獲取到String類型的redis對象
        ValueOperations<String, String> redisString = redisTemplate.opsForValue();
        
        //使用set方法,保存key和value的值
        redisString.set("city", "南京");
        
        //使用get(key)的方法獲取到city對應的值
        String string = redisString.get("city");
        System.out.println(string);
    }
    
}

圖形化界面:

技術分享

控制臺輸出:

技術分享

使用spring整合list類型的值

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    @Test
    public void Test01(){
        
        //通過模板獲取list類型的redis
        ListOperations<String, String> redisList = redisTemplate.opsForList();
        
        //通過key依次插入數據
        redisList.leftPush("city", "南京");
        redisList.leftPush("city", "上海");
        redisList.leftPush("city", "北京");
        redisList.leftPush("city", "上海");
        redisList.leftPush("city", "南京");
        
        //查找索引範圍內的所有數據
        List<String> range = redisList.range("city", 0, 10);
        System.out.println(range);
        
    }

}

圖形化客戶端:

技術分享

結果:

[南京, 上海, 北京, 上海, 南京]

使用spring整合Hash類型的值

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    @Test
    public void Test01(){
        
        //通過模板對象,獲取到redis的hash類型的對象
        HashOperations<String, Object, Object> redisMap = redisTemplate.opsForHash();
        
        //建立map集合
        Map<String, String> map=new HashMap<>();
        
        map.put("name", "小明");
        map.put("age", "18");
        map.put("length", "175");
        
        //存儲hash對象
        redisMap.putAll("people", map);
        
        //獲取數據庫中存儲的集合的key
        Set<Object> keys = redisMap.keys("people");
        //遍歷key集合,獲取到map中所有的value值
        for (Object key : keys) {
            Object value = redisMap.get("people", key);
            System.out.println(key+":"+value);
        }
    }
}

圖形化客戶端界面:

技術分享

取值後的控制臺界面:

name:小明
length:175
age:18

使用spring整合Set類型的值

代碼示例:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    @Test
    public void Test01(){
        //通過redis模板,創建set類型的redis對象
        SetOperations<String, String> redisSet = redisTemplate.opsForSet();
        
        //新建數組,賦值
        String[] arr=new String[5];
        arr[0]="南京";
        arr[1]="北京";
        arr[2]="南京";
        arr[3]="上海";
        arr[4]="北京";
        
        //調用set的add方法,存入key和數組
        redisSet.add("city", arr);
        
        //通過redis的獲取成員方法,利用key獲取到set集合
        Set<String> members = redisSet.members("city");
        System.out.println(members);
        
    }

}

圖形化數據客戶端界面:

技術分享

控制臺界面:

[北京, 南京, 上海]

由此可見,set類型的redis不是固定順序的.

使用spring整合sortSet類型的值

由於set類型是不具有順序的,而sortSet類型則具有順序

代碼示例:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    @Test
    public void Test01(){
        
        //使用模板創建ZSet對象
        ZSetOperations<String, String> redisZSet = redisTemplate.opsForZSet();
        
        //存值,存value的同時,還加上順序
        redisZSet.add("city", "南京", 1);
        redisZSet.add("city", "北京", 2);
        redisZSet.add("city", "上海", 3);
        redisZSet.add("city", "南京", 4);
        redisZSet.add("city", "上海", 5);
        redisZSet.add("city", "南京", 6);
        
        //獲取範圍順序裏面的值
        Set<String> rangeByScore = redisZSet.rangeByScore("city", 1, 10);
        System.out.println(rangeByScore);
        
    }

}

圖形化客戶端界面:

技術分享

控制臺數據:

[北京, 上海, 南京]

效果同之前一樣.

--end

Redis的基本使用(基於maven和spring)