修改redis.conf配置

1 注释掉bind

默认情况bind=127.0.0.1只能接受本机的访问请求

2 protected-mode

将本机访问保护模式设置no

连接

添加依赖

  1. <dependency>
  2. <groupId>redis.clients</groupId>
  3. <artifactId>jedis</artifactId>
  4. <version>3.2.0</version>
  5. </dependency>
  1. @Test
  2. public void demo1(){
  3. Jedis jedis = new Jedis("121.199.40.145",6379);
  4. jedis.set("name", "b");
  5. System.out.println(jedis.get("backup4"));
  6. System.out.println(jedis.ttl("name"));
  7. jedis.keys("*").forEach(System.out::println);
  8. }

实例

手机验证码功能
要求:
1、输入手机号,点击发送后随机生成6位数字码,2分钟有效
2、输入验证码,点击验证,返回成功或失败
3、每个手机号每天只能输入3次

  1. public class jedisDemo {
  2. public static void main(String[] args) {
  3. //模拟验证码发送
  4. verifyCode("156188");
  5. getRedisCode("156188","1943");
  6. }
  7. //验证码校验
  8. public static void getRedisCode(String phone,String code){
  9. Jedis jedis = new Jedis("121.199.40.145",6379);
  10. String codeKey = phone+":code";
  11. String redisCode = jedis.get(codeKey);
  12. if(redisCode.equals(code)){
  13. System.out.println("success");
  14. }else {
  15. System.out.println("failure");
  16. }
  17. }
  18. //每个手机每天只能发送三次,验证码放redis中,设置过期时间
  19. public static void verifyCode(String phone){
  20. Jedis jedis = new Jedis("121.199.40.145",6379);
  21. String countKey = phone+":count";
  22. String codeKey = phone+":code";
  23. //设置每天只能发送三次
  24. String count = jedis.get(countKey);
  25. if(count == null){
  26. //首次发送
  27. jedis.setex(countKey, 24 * 60 * 60, "1");
  28. }else if(Integer.parseInt(count)<=2){
  29. //发送次数+1
  30. jedis.incr(countKey);
  31. }else if(Integer.parseInt(count)==3){
  32. //达到三次
  33. System.out.println("发送次数到三次了");
  34. jedis.close();
  35. }
  36. String vcode = getCode();
  37. jedis.setex(codeKey, 120, vcode);
  38. jedis.close();
  39. }
  40. //生成验证码
  41. public static String getCode(){
  42. Random random = new Random();
  43. String code = "";
  44. for (int i = 0; i < 5; i++) {
  45. int m = random.nextInt(10);
  46. code+=m;
  47. }
  48. return code;
  49. }
  50. }

springBoot整合redis

引入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <!-- spring2.X集成redis所需common-pool2-->
  6. <dependency>
  7. <groupId>org.apache.commons</groupId>
  8. <artifactId>commons-pool2</artifactId>
  9. <version>2.6.0</version>
  10. </dependency>

配置文件

  1. spring:
  2. redis:
  3. # Redis服务器地址
  4. host: 121.199.40.145
  5. port: 6379
  6. # Redis数据库索引(默认为0
  7. database: 0
  8. # 连接超时时间(毫秒)
  9. timeout: 1800000
  10. #默认使用lettuce连接
  11. lettuce:
  12. pool:
  13. # 连接池最大连接数(使用负值表示没有限制)
  14. max-active: 20
  15. # 最大阻塞等待时间(负数表示没限制)
  16. max-wait: -1
  17. # 连接池中的最大空闲连接
  18. max-idle: 5
  19. # 连接池中的最小空闲连接
  20. min-idle: 0

Jedis
Jedis 是直连模式,在多个线程间共享⼀个 Jedis 实例时是线程不安全的,需要使⽤连接池,为每个jedis实例分配一个连接 。使⽤阻塞的I/O,⽅法调⽤同步,程序流需要等到socket处理完I/O才能执⾏,不⽀持异步操作

Lettuce
Lettuce底层使用的是Netty,当有多个线程都需要连接Redis服务器的时候,可以保证只创建一个Lettuce连接,使所有的线程共享这一个Lettuce连接,这样可以减少创建关闭一个Lettuce连接时候的开销;而且这种方式也是线程安全的,可以在多个线程间并发访问, 通过异步的⽅式可以更好的利用系统资源

  1. #可以通过排除lettuce的包依赖 切换成jedis连接
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. <exclusions>
  6. <exclusion>
  7. <groupId>io.lettuce</groupId>
  8. <artifactId>lettuce-core</artifactId>
  9. </exclusion>
  10. </exclusions>
  11. </dependency>
  12. <dependency>
  13. <groupId>redis.clients</groupId>
  14. <artifactId>jedis</artifactId>
  15. </dependency>

创建配置类(固定模板)

对象缓存入redis要注意序列化的格式

不同的序列化方式性能不一样

  • 采用默认的jdk方式会乱码(POJO类需要实现Serializable接口)
  • 采用JSON方式则不用序列化

JdkSerializationRedisSerializer

  • pojo对象的存取场景,使用JDK本身序列化机制
  • 默认机制ObjectinputStream/0bjectOutputStream进行序列化操作

StringRedisSerializer

  • Key或者value为字符串时使用

Jackson2JsonRedisSerializer

  • 利用jacksonjson工具,将pojo实例序列化成json格式存储

GenericFastJsonRedisSerializer

  • 另一种javabean与json之间的转换, 同时也需要指定Class类型 ```java @Configuration public class RedisConfig extends CachingConfigurerSupport { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
    1. RedisTemplate<String, Object> template = new RedisTemplate<>();
    2. RedisSerializer<String> redisSerializer = new StringRedisSerializer();
    3. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    4. ObjectMapper om = new ObjectMapper();
    5. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    6. // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,
    7. //比如String,Integer等会跑出异常
    8. //om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    9. jackson2JsonRedisSerializer.setObjectMapper(om);
    10. template.setConnectionFactory(factory);
    11. //key序列化方式
    12. template.setKeySerializer(redisSerializer);
    13. //value序列化
    14. template.setValueSerializer(jackson2JsonRedisSerializer);
    15. //value hashmap序列化
    16. template.setHashValueSerializer(jackson2JsonRedisSerializer);
    17. return template;
    }

}

  1. **注:Jackson2JsonRedisSerializer反序列化是不可以将map解析成对象,可以在序列化时把对象转换成Json存入**
  2. ```java
  3. public User test() {
  4. User user = new User("hhh这里", 21);
  5. System.out.println(user);
  6. //存入redis时先做了把对象转换成json
  7. redisTemplate.opsForValue().set("user用户", JSON.toJSONString(user));
  8. User redisUser = JSON.parseObject(String.valueOf(redisTemplate.opsForValue().get("user用户")), User.class);
  9. return redisUser;
  10. }