Redis_Jedis_测试

本文涉及的产品
云原生内存数据库 Tair,内存型 2GB
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Redis 版,经济版 1GB 1个月
简介: Redis_Jedis_测试

7.1. Jedis所需要的jar包

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

7.2. 连接Redis注意事项

禁用Linux的防火墙:Linux(CentOS7)里执行命令

systemctl stop/disable firewalld.service

redis.conf中注释bind 127.0.0.1 ,然后 protected-mode no

package com.jerry.jedis;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import java.util.Set;
/**
 * @author 金阳
 * @description
 * @create 2022-05-30 14:45
 */
public class JedisDemo1 {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.93.134",6379);
        String ping = jedis.ping();
        System.out.println(ping);
    }
    @Test
    public void demo1(){
        Jedis jedis = new Jedis("192.168.93.131",6379);
        jedis.set("k1","v1");
        String k1 = jedis.get("k1");
        System.out.println(k1);
        for (String key : jedis.keys("*")) {
            System.out.println(key);
        }
    }
    @Test
    public void demo2(){
        Jedis jedis = new Jedis("192.168.93.131",6379);
//        jedis.mset("str1","v1","str2","v2","str3","v3");
//        System.out.println(jedis.mget("str1","str2","str3"));
//        jedis.sadd("names","k1","k2");
//        Set<String> names = jedis.smembers("names");
//        System.out.println(names);
//        jedis.hset("users","age","20");
//        String hget = jedis.hget("user", "age");
//        System.out.println(hget);
        jedis.zadd("China",100d,"shanghai");
        Set<String> zrange = jedis.zrange("China", 0, -1);
        System.out.println(zrange);
    }
}

8. Redis_Jedis_实例

8.1. 完成一个手机验证码功能

要求:

1、输入手机号,点击发送后随机生成6位数字码,2分钟有效

2、输入验证码,点击验证,返回成功或失败

3、每个手机号每天只能输入3次

package com.jerry.jedis;
import redis.clients.jedis.Jedis;
import java.util.Random;
/**
 * @author 金阳
 * @description
 * @create 2022-06-01 15:08
 */
public class PhoneCode {
    public static void main(String[] args) {
        verifyCode("12345678901");
//        getRedisCode("12345678901","125641");
    }
    // 3验证码校验
    public static void getRedisCode(String phone, String code) {
        // 从redis中获取验证码
        Jedis jedis = new Jedis("192.168.93.134", 6379);
        // 验证码key
        String codeKey = "VerifyCode" + phone + ":code";
        String redisCode = jedis.get(codeKey);
        // 判断
        if (redisCode.equals(code)){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }
        jedis.close();
    }
    //2 每个手机每天只能发送3次,验证码放到redis中,设置过期时间
    public static void verifyCode(String phone) {
        // 连接redis
        Jedis jedis = new Jedis("192.168.93.134", 6379);
        // 拼接key
        // 手机发送次数key
        String countKey = "VerifyCode" + phone + ":count";
        // 验证码key
        String codeKey = "VerifyCode" + phone + ":code";
        // 每个手机每天只能发送三次
        String count = jedis.get(countKey);
        if (count == null) {
            jedis.setex(countKey, 24 * 60 * 60, "1");
        } else if (Integer.parseInt(count) <= 2) {
            jedis.incr(countKey);
        } else if (Integer.parseInt(count) > 2) {
            // 超过3次,不能再发送了
            System.out.println("今天发送次数已经超过3次");
            jedis.close();
            return;
        }
        // 发送验证码到redis里
        String vcode = getCode();
        jedis.setex(codeKey, 120, vcode);
        jedis.close();
    }
    //1生成6位数字随机验证码
    public static String getCode() {
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            int rand = random.nextInt(10);
            code += rand;
        }
        return code;
    }
}

9. Redis与Spring Boot整合

Spring Boot整合Redis非常简单,只需要按如下步骤整合即可

9.1. 整合步骤

1、 在pom.xml文件中引入redis相关依赖

<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- spring2.X集成redis所需common-pool2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.0</version>
</dependency>

2、 application.properties配置redis配置

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

3、 添加redis配置类

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
//key序列化方式
        template.setKeySerializer(redisSerializer);
//value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

4、测试一下

RedisTestController中添加测试方法

@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping
    public String testRedis() {
        //设置值到redis
        redisTemplate.opsForValue().set("name","lucy");
        //从redis获取值
        String name = (String)redisTemplate.opsForValue().get("name");
        return name;
    }
}


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
4天前
|
NoSQL Redis 数据安全/隐私保护
连接测试服务器redis
连接测试服务器redis
14 1
|
6天前
|
存储 缓存 NoSQL
Redis性能测试实操记录与分析
Redis性能测试实操记录与分析
12 3
|
1月前
|
监控 NoSQL 测试技术
解密Redis性能:如何通过性能测试提升系统稳定性和效率
解密Redis性能:如何通过性能测试提升系统稳定性和效率
|
1月前
|
NoSQL 测试技术 Redis
Redis【性能 02】Redis-5.0.14伪集群和Docker集群搭建及延迟和性能测试(均无法提升性能)
Redis【性能 02】Redis-5.0.14伪集群和Docker集群搭建及延迟和性能测试(均无法提升性能)
179 0
|
1月前
|
NoSQL 测试技术 Redis
Redis【性能 01】Redis 5.x 6.x 7.x 共5个不同版本延迟及性能测试对比分析(单机版默认配置)
Redis【性能 01】Redis 5.x 6.x 7.x 共5个不同版本延迟及性能测试对比分析(单机版默认配置)
276 0
|
7月前
|
存储 缓存 NoSQL
Redis性能测试实操记录与分析
通过对Redis性能测试的实操记录和分析,我们对Redis的性能表现有了更深入的了解。这种性能测试可以帮助我们评估Redis在不同负载下的表现,并根据测试结果采取相应的优化策略,以确保Redis在实际应用中能够满足性能需求,并提供高速的数据存储和缓存解决方案。
150 0
|
8月前
24Redis - 事务测试案例
24Redis - 事务测试案例
39 0
|
10月前
|
NoSQL Linux Redis
Linux系列——Redis的安装、测试
Linux系列——Redis的安装、测试
|
10月前
|
缓存 NoSQL 测试技术
【Redis】benchmark 测试工具
【Redis】benchmark 测试工具
|
11月前
|
缓存 NoSQL 前端开发
redis单机版安装+测试+项目运用
Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。