Redis之整合SpringBoot

超、凢脫俗 2022-05-09 14:20 319阅读 0赞

redis官方对Java语言的封装框架推荐有十多种,主要有:Jedis、Lettuce、Redisson

1几个框架的对比

三个框架都是在Java中对Redis操作的封装。

1.1 Jedis

Jedis是Redis的Java实现的客户端,其API提供了比较全面的Redis命令的支持。支持基本的数据类型如:String、Hash、List、Set、Sorted Set。
优点:比较全面的提供了Redis的操作特性,相比于其他Redis 封装框架更加原生。
编程模型: 使用阻塞的I/O,方法调用同步,程序流需要等到socket处理完I/O才能执行,不支持异步操作。Jedis客户端实例不是线程安全的,所以需要通过连接池来使用Jedis。

1.2 Lettuce

高级Redis客户端,用于线程安全同步,异步和响应使用,支持集群,Sentinel,管道和编码器。
优点:适合分布式缓存框架。
编程模型:基于Netty框架的事件驱动的通信层,其方法调用是异步的。Lettuce的API是线程安全的,所以可以操作单个Lettuce连接来完成各种操作(springboot2.0之后,redis的conn已经由jedis更改为lettuce)。

1.3 Redisson

Redisson实现了分布式和可扩展的Java数据结构。Redisson不仅提供了一系列的分布式Java常用对象,基本可以与Java的基本数据结构通用,还提供了许多分布式服务,其中包括(BitSet, Set, Multimap, SortedSet, Map, List, Queue, BlockingQueue, Deque, BlockingDeque, Semaphore, Lock, AtomicLong, CountDownLatch, Publish / Subscribe, Bloom filter, Remote service, Spring cache, Executor service, Live Object service, Scheduler service)
优点: 促使使用者对Redis的关注分离,让使用者能够将精力更集中地放在处理业务逻辑上,提供很多分布式相关操作服务,例如,分布式锁,分布式集合,可通过Redis支持延迟队列。
第三方框架整合

  • Redisson提供了和Spring框架的各项特性类似的,以Spring XML的命名空间的方式配置RedissonClient实例和它所支持的所有对象和服务
  • Redisson在Redis的基础上实现了Java缓存标准规范,并完整的实现了Spring框架里的缓存机制
  • Redisson提供了Spring Session会话管理器的实现

编程模型:基于Netty框架的事件驱动的通信层,其方法调用是异步的。Redisson的API是线程安全的,所以可以操作单个Redisson连接来完成各种操作。

RedisTemplate是Spring框架对Jedis和Lettuce的封装,让Spring框架体系能够更加方便的接入Redis的功能。RedisTemplate 同时支持 Jedis和Lettuce

一、Jedis

①pom.xml

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

②applicaton.properties

  1. #redis服务器地址
  2. jedis.pool.host=192.168.124.128
  3. #redis服务器端口
  4. jedis.pool.port=6379
  5. #redis的auth密码
  6. jedis.pool.password=123456
  7. #连接池最大连接数(使用负值表示没有限制)
  8. jedis.pool.config.maxTotal=60
  9. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  10. jedis.pool.config.maxWait=100
  11. #最大空闲连接
  12. jedis.pool.config.maxIdle=50
  13. #最小空闲连接
  14. jedis.pool.config.minIdle=0

③JedisConfig

  1. package com.yj.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.beans.factory.annotation.Qualifier;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import redis.clients.jedis.JedisPool;
  8. import redis.clients.jedis.JedisPoolConfig;
  9. import redis.clients.jedis.Protocol;
  10. @Configuration
  11. public class JedisConfig {
  12. @Bean(name = "jedis.pool")
  13. @Autowired
  14. public JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config,
  15. @Value("${jedis.pool.host}") String host, @Value("${jedis.pool.port}") int port,
  16. @Value("${jedis.pool.password}") String password) {
  17. return new JedisPool(config, host, port, Protocol.DEFAULT_TIMEOUT, password);
  18. }
  19. @Bean(name = "jedis.pool.config")
  20. public JedisPoolConfig jedisPoolConfig(@Value("${jedis.pool.config.maxTotal}") int maxTotal,
  21. @Value("${jedis.pool.config.maxWait}") int maxWait,
  22. @Value("${jedis.pool.config.maxIdle}") int maxIdle,@Value("${jedis.pool.config.minIdle}") int minIdle) {
  23. JedisPoolConfig config = new JedisPoolConfig();
  24. config.setMaxTotal(maxTotal);
  25. config.setMaxWaitMillis(maxWait);
  26. config.setMaxIdle(maxIdle);
  27. config.setMinIdle(minIdle);
  28. return config;
  29. }
  30. }

二、JedisCluster

①pom.xml

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

②application.properties

  1. # Redis服务器地址
  2. spring.redis.cluster.nodes=192.168.124.128:7000,192.168.124.128:7001,192.168.124.128:7002,192.168.124.128:7006,192.168.124.129:7003,192.168.124.129:7004,192.168.124.129:7005,192.168.124.129:7007
  3. # Redis服务器密码
  4. spring.redis.cluster.password=123456
  5. # 连接池最大连接数(使用负值表示没有限制)
  6. spring.redis.pool.max-active=60
  7. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  8. spring.redis.pool.max-wait=100
  9. # 连接池中的最大空闲连接
  10. spring.redis.pool.max-idle=50
  11. # 连接池中的最小空闲连接
  12. spring.redis.pool.min-idle=0
  13. # 连接超时时间(毫秒)
  14. spring.redis.timeout=200

③JedisClusterConfig

  1. package com.yj.config;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.util.StringUtils;
  8. import redis.clients.jedis.HostAndPort;
  9. import redis.clients.jedis.JedisCluster;
  10. import redis.clients.jedis.JedisPoolConfig;
  11. @Configuration
  12. public class JedisClusterConfig {
  13. @Value("${spring.redis.cluster.nodes}")
  14. private String clusterNodes;
  15. @Value("${spring.redis.cluster.password:}")
  16. private String password;
  17. @Value("${spring.redis.timeout}")
  18. private int timeout;
  19. @Value("${spring.redis.pool.max-idle}")
  20. private int maxIdle;
  21. @Value("${spring.redis.pool.max-active}")
  22. private int maxActive;
  23. @Value("${spring.redis.pool.max-wait}")
  24. private long maxWaitMillis;
  25. @Value("${spring.redis.commandTimeout:5000}")
  26. private int commandTimeout;
  27. @Value("${spring.redis.socketTimeout:1000}")
  28. private int socketTimeout;
  29. @Value("${spring.redis.maxAttempts:1000}")
  30. private int maxAttempts;
  31. @Bean
  32. public JedisCluster getJedisCluster() {
  33. String[] cNodes = clusterNodes.split(",");
  34. Set<HostAndPort> nodes = new HashSet<HostAndPort>();
  35. for(String node : cNodes) {
  36. String[] hp = node.split(":");
  37. nodes.add(new HostAndPort(hp[0],Integer.parseInt(hp[1])));
  38. }
  39. JedisPoolConfig jedisPoolConfig =new JedisPoolConfig();
  40. jedisPoolConfig.setMaxIdle(maxIdle);
  41. jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
  42. jedisPoolConfig.setMaxTotal(maxActive);
  43. if (StringUtils.isEmpty(password)) {
  44. return new JedisCluster(nodes, commandTimeout, jedisPoolConfig);
  45. }
  46. return new JedisCluster(nodes, commandTimeout, socketTimeout, maxAttempts, password, jedisPoolConfig);
  47. }
  48. }

三、RedisTemple

分为RedisTemple和StringRedisTemple

①pom.xml

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-redis</artifactId>
  4. <version>1.3.2.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>fastjson</artifactId>
  9. <version>1.2.16</version>
  10. </dependency>

②application.properties

  1. # Redis服务器地址
  2. spring.redis.hostName=192.168.124.128
  3. # Redis服务器连接端口
  4. spring.redis.port=6379
  5. # Redis服务器连接密码
  6. spring.redis.password=123456
  7. # Redis数据库索引(默认为0)
  8. spring.redis.database=0
  9. # 连接池最大连接数(使用负值表示没有限制)
  10. spring.redis.pool.max-active=60
  11. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  12. spring.redis.pool.max-wait=100
  13. # 连接池中的最大空闲连接
  14. spring.redis.pool.max-idle=50
  15. # 连接池中的最小空闲连接
  16. spring.redis.pool.min-idle=0
  17. # 连接超时时间(毫秒)
  18. spring.redis.timeout=200

③RedisTemplateConfig

  1. package com.yj.config;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.boot.context.properties.ConfigurationProperties;
  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.connection.jedis.JedisConnectionFactory;
  9. import org.springframework.data.redis.core.RedisTemplate;
  10. import org.springframework.data.redis.core.StringRedisTemplate;
  11. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  12. import org.springframework.data.redis.serializer.StringRedisSerializer;
  13. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  14. import com.fasterxml.jackson.annotation.PropertyAccessor;
  15. import com.fasterxml.jackson.databind.ObjectMapper;
  16. import redis.clients.jedis.JedisPoolConfig;
  17. @Configuration
  18. public class RedisTemplateConfig {
  19. private Logger logger = LoggerFactory.getLogger(RedisTemplateConfig.class);
  20. @Bean
  21. @ConfigurationProperties(prefix="spring.redis")
  22. public JedisPoolConfig getRedisConfig(){
  23. JedisPoolConfig config = new JedisPoolConfig();
  24. return config;
  25. }
  26. @Bean
  27. @ConfigurationProperties(prefix="spring.redis")
  28. public JedisConnectionFactory getConnectionFactory(){
  29. JedisConnectionFactory factory = new JedisConnectionFactory();
  30. JedisPoolConfig config = getRedisConfig();
  31. factory.setPoolConfig(config);
  32. logger.info("JedisConnectionFactory bean init success");
  33. return factory;
  34. }
  35. @Bean
  36. public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
  37. RedisTemplate<Object, Object> template = new RedisTemplate<>();
  38. template.setConnectionFactory(connectionFactory);
  39. // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
  40. Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
  41. ObjectMapper mapper = new ObjectMapper();
  42. mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  43. mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  44. serializer.setObjectMapper(mapper);
  45. template.setValueSerializer(serializer);
  46. // 使用StringRedisSerializer来序列化和反序列化redis的key值
  47. template.setKeySerializer(new StringRedisSerializer());
  48. template.afterPropertiesSet();
  49. return template;
  50. }
  51. @Bean
  52. public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
  53. StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
  54. stringRedisTemplate.setConnectionFactory(factory);
  55. return stringRedisTemplate;
  56. }
  57. }

使用

  1. package com.yj;
  2. import java.util.Date;
  3. import org.junit.Test;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.data.redis.core.RedisTemplate;
  8. import com.alibaba.fastjson.JSON;
  9. import com.alibaba.fastjson.JSONObject;
  10. import com.yj.entity.User;
  11. import redis.clients.jedis.Jedis;
  12. import redis.clients.jedis.JedisCluster;
  13. import redis.clients.jedis.JedisPool;
  14. public class RedisClientTest extends ApplicationTest {
  15. private Logger logger = LoggerFactory.getLogger(ClientTest.class);
  16. @Autowired
  17. private JedisPool jedisPool;
  18. @Autowired
  19. private JedisCluster jedisCluster;
  20. @Autowired
  21. private RedisTemplate<String, Object> redisTemplate;
  22. @Autowired
  23. private RedisTemplate<String, String> stringRedisTemplate;
  24. @Test
  25. public void testJedis() {
  26. Jedis jedis = jedisPool.getResource();
  27. jedis.set("Jedis", JSON.toJSONString(getUser()));
  28. String userStr = jedis.get("Jedis");
  29. User value = JSONObject.parseObject(userStr, User.class);
  30. logger.info("Jedis:" + value);
  31. }
  32. @Test
  33. public void testJedisCluster() {
  34. jedisCluster.set("JedisCluster", JSON.toJSONString(getUser()));
  35. String userStr = jedisCluster.get("JedisCluster");
  36. User value = JSONObject.parseObject(userStr, User.class);
  37. logger.info("JedisCluster:" + value);
  38. }
  39. @Test /* 模板Bean已经配置了序列化和反序列化的策略 */
  40. public void testRedisTemplate() {
  41. redisTemplate.opsForValue().set("redisTemplate", getUser());
  42. User value = (User) redisTemplate.opsForValue().get("redisTemplate");
  43. logger.info("RedisTemplate:" + value);
  44. }
  45. @Test
  46. public void testStringRedisTemplate() {
  47. stringRedisTemplate.opsForValue().set("StringRedisTemplate", JSON.toJSONString(getUser()));
  48. String value = stringRedisTemplate.opsForValue().get("StringRedisTemplate");
  49. logger.info("StringRedisTemplate:" + value);
  50. }
  51. private User getUser() {
  52. User user = new User();
  53. user.setName("yj");
  54. user.setAge(18);
  55. user.setDate(new Date());
  56. return user;
  57. }
  58. }

发表评论

表情:
评论列表 (有 0 条评论,319人围观)

还没有评论,来说两句吧...

相关阅读