redis入门

下载安装redis ,启动redis-server 服务

springboot 集成redis 

项目结构:

 

 

 

application.yml

##端口号
server.port=8888

# Redis数据库索引(默认为0)
spring.redis.database=0 
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379 
# Redis服务器连接密码(默认为空)
spring.redis.password=
#连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8 
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1 
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8 
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0 
# 连接超时时间(毫秒)
spring.redis.timeout=300

 

RedisConfig.java

package com.wanjun.redis.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
@EnableCaching // 开启注解
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }
}

 

 

Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)

分别对五种数据结构进行一个 读写操作,便于理解

 

 

创建RedisController.java

一、测试 String类型

@RequestMapping("/string")
    public void redisString() throws InterruptedException {
        redisTemplate.opsForValue().set("name", "小污龟", 1, TimeUnit.SECONDS); // 设置1秒后过期
        String string = (String) redisTemplate.opsForValue().get("name");
        System.out.println(string);
        Thread.sleep(1000);
        // 1秒后重新获取
        String string2 = (String) redisTemplate.opsForValue().get("name");
        System.out.println(string2);
    }

浏览器输入:http://localhost:8888/redis/string

控制台输出:

小污龟
null

 

二、测试 list

 

@RequestMapping("/list")
    public void redisList() throws InterruptedException {
        List<UserEntity> userList = new ArrayList<>();
        UserEntity user1 = new UserEntity();
        user1.setAge("18");
        UserEntity user2 = new UserEntity();
        user2.setAge("19");
        userList.add(user1);
        userList.add(user2);
        redisTemplate.opsForList().leftPushAll("user", userList);
        List<UserEntity> leftPop = (List<UserEntity>) redisTemplate.opsForList().leftPop("user");
        leftPop.forEach((userEntry)->System.out.println(userEntry.getAge()));
    }

浏览器输入:http://localhost:8888/redis/list

控制台输出:

18
19

三、测试 hash    保存和读取map

@RequestMapping("/hash")
    public void redisHash() throws InterruptedException {
        Map<String, String> userMap = new HashMap<>();
        userMap.put("id", "1");
        userMap.put("name", "小乌龟");
        userMap.put("pwd", "123456");
        userMap.put("sex", "男");
        redisTemplate.opsForHash().putAll("map", userMap);
        Map<Object, Object> entries = redisTemplate.opsForHash().entries("map");
        List<Object> reslutMapList = redisTemplate.opsForHash().values("map");
        Set<Object> resultMapSet = redisTemplate.opsForHash().keys("map");
        String name = (String) redisTemplate.opsForHash().get("map", "name");

        System.out.println("entries:" + entries);
        System.out.println("reslutMapList:" + reslutMapList);
        System.out.println("resultMapSet:" + resultMapSet);
        System.out.println("name:" + name);

    }

 

浏览器输入:http://localhost:8888/redis/hash

控制台输出:

entries:{sex=男, name=小乌龟, id=1, pwd=123456}
reslutMapList:[男, 小乌龟, 1, 123456]
resultMapSet:[sex, name, id, pwd]
name:小乌龟

 

 

四、测试Set  不重复的对象

@RequestMapping("/set")
    public void redisSet() throws InterruptedException {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add("set1", "22");
        set.add("set1", "33");
        set.add("set1", "44");
        set.add("set1", "44");
        Set<Object> resultSet = redisTemplate.opsForSet().members("set1");
        System.out.println("resultSet:" + resultSet);
    }

浏览器输入:http://localhost:8888/redis/set

控制台输出:

resultSet:[44, 33, 22]

 

五、测试ZSet

ZSet 用来对一个集合根据每个对象的score 进行有序排序,比如积分排行榜功能

比如有个 money的字段的集合,里面有 张三 90000 元,李四 85001元....

现在根据他们的资产进行由大到小排行。

package com.wanjun.redis.controller;

import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("/zset")
    public void redisZSet() throws InterruptedException {
        ZSetOperations<String, Object> opsForZSet = redisTemplate.opsForZSet();
        opsForZSet.add("money", "zhangsan", 90000);
        opsForZSet.add("money", "lisi", 85001);
        opsForZSet.add("money", "wangwu", 65324.9);
        opsForZSet.add("money", "zhaoliu", 32122);
        Set<TypedTuple<Object>> rangeWithScores = opsForZSet.reverseRangeWithScores("money", 0, -1);
        Long rank = opsForZSet.rank("money", "lisi");
        System.out.println("lisi排名:" + rank);
        rangeWithScores.forEach((a) -> System.out.println(a.getValue() + " " + a.getScore()));
    }
}

浏览器输入:http://localhost:8888/redis/zset

控制台输出:

lisi排名:2
zhangsan 90000.0
lisi 85001.0
wangwu 65324.9
zhaoliu 32122.0

 

代码下载:https://github.com/wanun/redis

posted @ 2020-05-01 14:18  小污龟  阅读(185)  评论(0编辑  收藏  举报