当前位置:   article > 正文

springboot连接redis

springboot连接redis

1.连接redis--2014

默认有三种方式连接redis.

第一种:jedis---传统的项目--ssm

第二种:lettuce:---->刚出现没有多久就被springboot整合进来。

第三种:springboot连接redis

1.1 jedis操作redis服务器

(1)引入jedis依赖

  1. <dependency>
  2.   <groupId>redis.clients</groupId>
  3.   <artifactId>jedis</artifactId>
  4.   <version>4.3.1</version>
  5. </dependency>

(2)编写相关的代码

  1. void testJedis(){
  2.  Jedis jedis=new Jedis("192.168.1.87",6379);
  3.        //该类包含很多对redis操作的方法--而这些方法和原来我们使用的命令一样。
  4.        Set<String> keys = jedis.keys("*");
  5.        System.out.println(keys);
  6.        //对string数据类型操作
  7.        String set = jedis.set(;"k3", "zmz");
  8.        System.out.println("set"+set);
  9.        String v3 = jedis.get("k3");
  10.        System.out.println("v3:"+v3);
  11.        jedis.setex("s1",99,"jsl");
  12.    jedis.close();
  13. }

每次使用jedis对象时 都需要自己创建,当使用完后,需要关闭该对象。===>jedis中也存在连接池.

1.2 jedis连接池的使用

  1. //连接池的配置信息
  2.        JedisPoolConfig config=new JedisPoolConfig();
  3.        config.setMaxTotal(100);//最多的连接个数
  4.        config.setMaxIdle(10); //最多空闲的连接个数
  5.        config.setMinIdle(2); //最小的空闲个数
  6.        config.setTestOnBorrow(true);//在获取连接对象时是否验证该连接对象的连通性
  7. //创建连接池对象
  8.        JedisPool jedisPool=new JedisPool(config,"192.168.1.87",6379);
  9. long start = System.currentTimeMillis();
  10.        for(int i=0;i<1000;i++){
  11.            Jedis jedis = jedisPool.getResource();
  12.            String ping = jedis.ping();
  13.            jedis.close();
  14.       }
  15.        long end = System.currentTimeMillis();
  16.        System.out.println("耗时:"+(end-start));
  17. long start = System.currentTimeMillis();
  18.        //Jedis(String host, int port)
  19.        for(int i=0;i<1000;i++){
  20.            Jedis jedis=new Jedis("192.168.1.87",6379);
  21.            String ping = jedis.ping();
  22.            jedis.close();
  23.       }
  24.        long end = System.currentTimeMillis();
  25.        System.out.println("耗时:"+(end-start));

1.3 springboot整合redis

springboot在整合redis时提高两个模板类,StringRedisTemplate和RedisTemplate.以后对redis的操作都在该模板类中。StringRedisTemplate是RedisTemplate的子类。

  1. <!--redis相关的依赖-->
  2.        <dependency>
  3.            <groupId>org.springframework.boot</groupId>
  4.            <artifactId>spring-boot-starter-data-redis</artifactId>
  5.        </dependency>
  6.        <dependency>
  7.            <groupId>org.apache.commons</groupId>
  8.            <artifactId>commons-pool2</artifactId>
  9.        </dependency>

修改配置文件

  1. #redis的配置信息
  2. spring.redis.host=192.168.1.87
  3. spring.redis.port=6379
  4. #最多获取数
  5. spring.redis.lettuce.pool.max-active=8
  6. spring.redis.lettuce.pool.max-wait=-1ms
  7. spring.redis.lettuce.pool.max-idle=8
  8. spring.redis.lettuce.pool.min-idle=0
  1. //因为springboot整合redis时会把StringRedisTemplate创建并交于spring容器管理
  2.    @Autowired
  3.    private StringRedisTemplate redisTemplate;
  4.    @Test
  5.    void contextLoads() {
  6.        //关于key的操作
  7.        Set<String> keys = redisTemplate.keys("*");//获取所有的key
  8.        System.out.println("keys:"+keys);
  9.        Boolean hasKey = redisTemplate.hasKey("k1");//判断是否存在指定的key
  10.        System.out.println("判断是否存在指定的key:"+hasKey);
  11.        Boolean k1 = redisTemplate.delete("k1");//删除指定的key
  12.        System.out.println("是否删除指定key成功:"+k1);
  13.        //操作Stirng------StringRedisTemplate会把对每一种数据的操作单独封装成一个类。
  14.        ValueOperations<String, String> forValue = redisTemplate.opsForValue();//ValueOperations专门操作字符串
  15.        forValue.set("k2","张明喆");
  16.        String k2 = forValue.get("k2");
  17.        System.out.println("k2:"+k2);
  18.        //只有在 key 不存在时设置 key 的值。
  19.        Boolean aBoolean = forValue.setIfAbsent("k2", "zmz2");
  20.        System.out.println("是否存入成功:"+aBoolean);
  21.        //incr decr
  22.        Long k4 = forValue.increment("k4",20);
  23.        System.out.println("k4:"+k4);
  24.        //decr 将 key 中储存的数字值减一
  25.        forValue.decrement("k4");
  26.        //批量添加
  27.        Map<String,String> map=new HashMap<>();
  28.        map.put("m1","m1");
  29.        map.put("m2","m2");
  30.        forValue.multiSet(map);
  31.        //hash操作
  32.        HashOperations<String, Object, Object> forHash = redisTemplate.opsForHash();
  33.        forHash.put("k5", "name", "zmz");
  34.        forHash.put("k5", "age", "16");
  35.        forHash.put("k5", "sex", "男");
  36.        Map<String, String> map1 = new HashMap<>();
  37.        map.put("name", "jsl");
  38.        map.put("age", "29");
  39.        map.put("sex", "男");
  40.        forHash.putAll("k6", map1);
  41.        Map<Object, Object> k5 = forHash.entries("k5");
  42.        System.out.println(k5);
  43.        Set<Object> k6 = forHash.keys("k6");
  44.        System.out.println(k6);
  45.        System.out.println(forHash.values("k6"));
  46.        //list操作
  47.        ListOperations<String, String> list = redisTemplate.opsForList();
  48.        //放入单个 key value
  49.        list.leftPush("l1","111");
  50.        //放入 批量value
  51.        list.leftPushAll("l2","zmz","jsl","hql","fxd");
  52.        //获取列表指定范围内的元素
  53.        List<String> l2 = list.range("l2", 0, -1);
  54.        System.out.println(l2);
  55.        //移出并获取列表的第一个元素
  56.        list.leftPop("l2");
  57.        //set 无序不允许重复.
  58.        SetOperations<String, String> forSet = redisTemplate.opsForSet();
  59.        //向集合添加一个或多个成员
  60.        forSet.add("s1","张明喆","贾善领","黄启龙","张明喆","贾善领");
  61.        forSet.add("s2","张明喆1","贾善领2","黄启龙3","张明喆","贾善领");
  62.        //返回集合中的所有成员
  63.        Set<String> s1 = forSet.members("s1");
  64.        System.out.println(s1);
  65.        //随机获取一个或多个元素
  66.        String s11 = forSet.randomMember("s1");
  67.        System.out.println(s11);
  68.        //返回给定所有集合的交集
  69.        Set<String> intersect = forSet.intersect("s1", "s2");
  70.        System.out.println(intersect);
  71.        //sort set操作
  72.        ZSetOperations<String, String> forZSet = redisTemplate.opsForZSet();
  73.        //向有序集合添加一个或多个成员,或者更新已存在成员的分数
  74.        forZSet.add("z1","math",80);
  75.        forZSet.add("z1","chinese",99);
  76.        forZSet.add("z1","english",78);
  77.        forZSet.add("z1","physics",76);
  78.        forZSet.add("z1","biology",60);
  79.        //通过索引区间返回有序集合成指定区间内的成员
  80.        Set<String> z1 = forZSet.range("z1", 0, -1);
  81.        System.out.println(z1);
  82.        //返回有序集合中指定成员的排名,有序集成员按分数值递减(从大到小)排序
  83.        Set<String> z11 = forZSet.reverseRange("z1", 0, -1);
  84.        System.out.println(z11);
  85.   }

1.4RedisTemplate

它是StringRedisTemplate的父类,它类可以存储任意数据类型,但是任意类型必须序列化,默认采用的是jdk的序列化方式。jdk序列化方式阅读能力差,而且占用空间大. 我们在使用是一般需要人为指定序列化方式。

  1. public class SpringbootRedisApplicationTests2 {
  2.    @Autowired
  3.    private RedisTemplate redisTemplate;
  4.    @Test
  5.    void test1(){
  6.        ValueOperations valueOperations = redisTemplate.opsForValue();
  7.        valueOperations.set("user",new User("张明喆",29,"上海"));
  8.        Object o = valueOperations.get("user");
  9.        System.out.println(o);
  10.        HashOperations hashOperations = redisTemplate.opsForHash();
  11.        hashOperations.put("k3","name","zmz");
  12.        Map<String, Object> map = new HashMap<>();
  13.        map.put("1", new User("zz",22,"ll"));
  14.        hashOperations.putAll("k5", map);
  15.   }
  16. }

如果每次使用都人为指定序列化方式,统一设置redisTemplate的序列化

  1. package com.sws;
  2. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  3. import com.fasterxml.jackson.annotation.PropertyAccessor;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.data.redis.connection.RedisConnectionFactory;
  8. import org.springframework.data.redis.core.RedisTemplate;
  9. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  10. import org.springframework.data.redis.serializer.RedisSerializer;
  11. import org.springframework.data.redis.serializer.StringRedisSerializer;
  12. /**
  13. * @program: springboot-redis
  14. * @description:
  15. * @author:
  16. * @create: 2023-04-24 16:24
  17. **/
  18. @Configuration
  19. public class RedisConfig {
  20. //比如验证码
  21. @Bean //该方法的返回对象交于spring容器管理
  22. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  23. RedisTemplate<String, Object> template = new RedisTemplate<>();
  24. RedisSerializer<String> redisSerializer = new StringRedisSerializer();
  25. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  26. ObjectMapper om = new ObjectMapper();
  27. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  28. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  29. jackson2JsonRedisSerializer.setObjectMapper(om);
  30. template.setConnectionFactory(factory);
  31. //key序列化方式
  32. template.setKeySerializer(redisSerializer);
  33. //value序列化
  34. template.setValueSerializer(jackson2JsonRedisSerializer);
  35. //value hashmap序列化
  36. template.setHashValueSerializer(jackson2JsonRedisSerializer);
  37. template.setHashKeySerializer(redisSerializer);
  38. return template;
  39. }
  40. }

1.5 springboot连接集群

  1. spring.redis.lettuce.pool.max-active=8
  2. spring.redis.lettuce.pool.max-wait=-1ms
  3. spring.redis.lettuce.pool.max-idle=8
  4. spring.redis.lettuce.pool.min-idle=0
  5. # 设置redis重定向的次数---根据主节点的个数
  6. spring.redis.cluster.max-redirects=3
  7. spring.redis.cluster.nodes=192.168.1.87:7001,192.168.1.87:7002,192.168.1.87:7003,192.168.1.87:7004,192.168.1.87:7005,192.168.1.87:7006

2.redis的应用场景

2.1. redis可以作为缓存

(1) 缓存的原理

 

(2)缓存的作用:

减少访问数据库的频率。--提高系统的性能。

(3)什么样的数据适合放入缓存

  1. 查询频率高的

  2. 修改频率低的

  3. 数据安全性要求低的。

(4)如何使用缓存

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.3.12.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.ykq</groupId>
  12. <artifactId>qy163-springboot-redis02</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>qy163-springboot-redis02</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-data-redis</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.apache.commons</groupId>
  26. <artifactId>commons-pool2</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>com.baomidou</groupId>
  30. <artifactId>mybatis-plus-boot-starter</artifactId>
  31. <version>3.5.1</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-web</artifactId>
  36. </dependency>
  37. <dependency>
  38. <groupId>mysql</groupId>
  39. <artifactId>mysql-connector-java</artifactId>
  40. </dependency>
  41. <dependency>
  42. <groupId>org.projectlombok</groupId>
  43. <artifactId>lombok</artifactId>
  44. <optional>true</optional>
  45. </dependency>
  46. <dependency>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-starter-test</artifactId>
  49. <scope>test</scope>
  50. </dependency>
  51. </dependencies>
  52. <build>
  53. <plugins>
  54. <plugin>
  55. <groupId>org.springframework.boot</groupId>
  56. <artifactId>spring-boot-maven-plugin</artifactId>
  57. <configuration>
  58. <excludes>
  59. <exclude>
  60. <groupId>org.projectlombok</groupId>
  61. <artifactId>lombok</artifactId>
  62. </exclude>
  63. </excludes>
  64. </configuration>
  65. </plugin>
  66. </plugins>
  67. </build>
  68. </project>

(3)配置文件

  1. server.port=9999
  2. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  3. spring.datasource.url=jdbc:mysql:///aaa
  4. spring.datasource.username=root
  5. spring.datasource.password=17637422471
  6. #打印日志
  7. mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  8. #最多获取数
  9. spring.redis.lettuce.pool.max-active=8
  10. spring.redis.lettuce.pool.max-wait=-1ms
  11. spring.redis.lettuce.pool.max-idle=8
  12. spring.redis.lettuce.pool.min-idle=0
  13. # ??redis??????---????????
  14. spring.redis.cluster.max-redirects=3
  15. #redis的配置信息
  16. spring.redis.host=192.168.1.87
  17. spring.redis.port=6379

servie层

  1. package com.sws.service.impl;
  2. import com.sws.mapper.Student1Mapper;
  3. import com.sws.pojo.Student1;
  4. import com.sws.service.Student1Service;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.data.redis.core.RedisTemplate;
  7. import org.springframework.data.redis.core.ValueOperations;
  8. import org.springframework.stereotype.Service;
  9. import javax.annotation.Resource;
  10. /**
  11. * @program: springboot--redis
  12. * @description:
  13. * @author:
  14. * @create: 2023-04-24 18:07
  15. **/
  16. @Service
  17. public class Student1ServiceImpl implements Student1Service {
  18. @Resource
  19. private Student1Mapper student1Mapper;
  20. @Autowired
  21. private RedisTemplate<String,Object> redisTemplate;
  22. @Override
  23. public Student1 selectById(Integer id) {
  24. ValueOperations<String, Object> ops =redisTemplate.opsForValue();
  25. Object o = ops.get("student:" + id);
  26. if (o!=null){
  27. return (Student1) o;
  28. }
  29. Student1 student1 = student1Mapper.selectById(id);
  30. if (student1!=null){
  31. ops.set("student:"+id,student1);
  32. }
  33. return student1;
  34. }
  35. }
  36. public interface Student1Service {
  37. Student1 selectById(Integer id);
  38. }

controller层

  1. @RestController
  2. @RequestMapping("student")
  3. public class Student1Controller {
  4. @Resource
  5. private Student1Service student1Service;
  6. @GetMapping("selectById/{id}")
  7. public Student1 selectById(@PathVariable Integer id ){
  8. return student1Service.selectById(id);
  9. }
  10. }

config层配置类

  1. @Configuration
  2. public class RedisConfig {
  3. //比如验证码
  4. @Bean //该方法的返回对象交于spring容器管理
  5. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  6. RedisTemplate<String, Object> template = new RedisTemplate<>();
  7. RedisSerializer<String> redisSerializer = new StringRedisSerializer();
  8. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  9. ObjectMapper om = new ObjectMapper();
  10. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  11. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  12. jackson2JsonRedisSerializer.setObjectMapper(om);
  13. template.setConnectionFactory(factory);
  14. //key序列化方式
  15. template.setKeySerializer(redisSerializer);
  16. //value序列化
  17. template.setValueSerializer(jackson2JsonRedisSerializer);
  18. //value hashmap序列化
  19. template.setHashValueSerializer(jackson2JsonRedisSerializer);
  20. template.setHashKeySerializer(redisSerializer);
  21. return template;
  22. }
  23. }

mapper接口

  1. @Mapper
  2. public interface Student1Mapper extends BaseMapper<Student1> {
  3. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/890901
推荐阅读
相关标签
  

闽ICP备14008679号