zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

Spring Boot 项目集成Redis的方式详解

2023-06-13 09:19:49 时间
使用Jedis

Jedis是Redis官方推荐的面向Java的操作Redis的客户端,是对服务端直连后进行操作。如果直接使用Jedis进行连接,多线程环境下是非线程安全的,正式生产环境一般使用连接池进行连接。


 dependency 

 groupId redis.clients /groupId 

 artifactId jedis /artifactId 

 version 2.9.0 /version 

 /dependency 
使用spring-data-redis

由Spring 框架提供,是对Redis客户端的进一步封装,屏蔽了不同客户端的不同实现方式,让服务端和客户端进一步解耦;也就是你可以切换不同的客户端实现,比如Jedis或Lettuce(Redis客户端实现之一),而不影响你的业务逻辑。

类似于的SpringCloud的服务治理框架对不同服务治理组件的适配,或是AMQP

它利用RedisTemplate对JedisApi进行高度封装。使用的依赖如下:


 dependency 

 groupId org.springframework.boot /groupId 

 artifactId spring-boot-starter-data-redis /artifactId 

 /dependency 
Redis的安装

收先要安装Redis服务端,Redis官方提供的是Linux安装包。网上有很多详细的安装教程,这里不做展开。关于Windows下的安装,可参考我的另一篇博文windows下Redis的安装和使用

完成Redis服务端的安装之后,我们开始在项目中进行集成。这里我们先介绍使用Jedis的方式进行的集成。先按上面的提及的方式进行依赖的引入。然后将Redis的相关信息配置到配置文件中去。我们可以的新建一个配置文件redis.properties,内容如下:


# Redis数据库索引(默认为0)

spring.redis.database=0

# Redis服务器地址

spring.redis.host=127.0.0.1

# Redis服务器连接端口

spring.redis.port=6379

# Redis服务器连接密码(默认为空)

spring.redis.password=

# 连接超时时间(毫秒)

spring.redis.timeout=0

接下来我们要为Redis客户端连接绑定上面的配置,创建出来的客户端实例才能够连接到我们的想连的Redis服务端。你可以使用@Value注解或@ConfigurationProperties注解的方式,本文采用的是后者,如果还不清楚的该注解的用法,可以移步我的另一篇博文@ConfigurationProperties实现自定义配置绑定查看,这里不做展开。

以下是Redis服务端信息配置的接收类:MyRedisProperties.java


@ConfigurationProperties(

 prefix = "spring.redis"

@Component

@Data

@PropertySource("classpath:/redis.properties")

public class MyRedisProperties {

 private String database;

 private String host;

 private Integer port;

 private String password;

 private Integer timeOut;

}

由于我们正式生产环境一般都是采用连接池方式实现,所以我们还需要关于连接池的配置如下:


# 连接池最大连接数(使用负值表示没有限制)

spring.redis.pool.max-active=8

# 连接池最大阻塞等待时间(使用负值表示没有限制)

spring.redis.pool.max-wait=-1

# 连接池中的最大空闲连接

spring.redis.pool.max-idle=8

# 连接池中的最小空闲连接

spring.redis.pool.min-idle=0

对应的接收类如下:


@ConfigurationProperties(

 prefix = "spring.redis.pool"

@Data

@Component

@PropertySource("classpath:/redis.properties")

public class RedisPoolProperties {

 private Integer maxActive;

 private Integer maxWait;

 private Integer maxIdle;

 private Integer minIdle;

}

然后向Spring容器装配客户端实例,分为单个客户端和连接池两种实现,如下代码:


@Configuration

public class RedisConfig {

 @Autowired

 private RedisPoolProperties redisPoolProperties;

 @Autowired

 private MyRedisProperties myRedisProperties;

 @Bean

 public Jedis singleJedis(){

 return new Jedis(myRedisProperties.getHost(),myRedisProperties.getPort());

 @Bean

 public JedisPool jedisPool(){ 

 JedisPoolConfig poolConfig = new JedisPoolConfig();

 poolConfig.setMaxIdle(redisPoolProperties.getMaxIdle());

 poolConfig.setMaxTotal(redisPoolProperties.getMaxActive());

 poolConfig.setMaxWaitMillis(redisPoolProperties.getMaxWait() * 1000);

 JedisPool jp = new JedisPool(poolConfig, myRedisProperties.getHost(), myRedisProperties.getPort(),

 myRedisProperties.getTimeOut()*1000, myRedisProperties.getPassword(), 0);

 return jp;

}
获取Redis客户端

进行相关配置的绑定之后,意味着我们程序可以拿到Redis和连接池的相关信息,然后进行客户端的创建和连接了。所以我们要向Spring容器装配客户端实例,分为单个客户端和连接池两种实现,如下代码:


@Configuration

public class RedisConfig {

 @Autowired

 private RedisPoolProperties redisPoolProperties;

 @Autowired

 private MyRedisProperties myRedisProperties;

 @Bean

 public Jedis singleJedis(){

 return new Jedis(myRedisProperties.getHost(),myRedisProperties.getPort());

 @Bean

 public JedisPool jedisPool(){ 

 JedisPoolConfig poolConfig = new JedisPoolConfig();

 poolConfig.setMaxIdle(redisPoolProperties.getMaxIdle());

 poolConfig.setMaxTotal(redisPoolProperties.getMaxActive());

 poolConfig.setMaxWaitMillis(redisPoolProperties.getMaxWait() * 1000);

 JedisPool jp = new JedisPool(poolConfig, myRedisProperties.getHost(), myRedisProperties.getPort(),

 myRedisProperties.getTimeOut()*1000, myRedisProperties.getPassword(), 0);

 return jp;

}
Redis工具的编写

装配好客户端实例后,我们就可以通过@Autowired的方式进行注入使用了。我们都知道,Redis有5中数据类型,分别是:

string(字符串) hash(哈希) list(列表) set(集合) zset(sorted set:有序集合)

所以的有必要的封装一个操作者5种数据列表的工具类,由于篇幅的关系,我们以Redis最基本的数据类型String为例,简单封装几个操作方法作为示例如下,更详细的封装,可参考java操作Redis数据库的redis工具,RedisUtil,jedis工具JedisUtil,JedisPoolUtil这一博文


@Service

public class RedisService {

 @Autowired

 private JedisPool jedisPool; // 连接池方式

 @Autowired

 private Jedis myJedis; // 单个客户端

 public T T get(String key, Class T clazz) {

 Jedis jedis = null;

 try {

 jedis = jedisPool.getResource();

 String str = jedis.get(key);

 return stringToBean(str,clazz);

 } finally {

 close(jedis);

 public T void set(String key, T value) {

 try {

 String str = value.toString();

 if (str == null || str.length() = 0) {

 return;

 myJedis.set(key, str);

 } finally {

 close(myJedis);

 private void close(Jedis jedis) {

 if (jedis != null) {

 jedis.close();

 * 把一个字符串转换成bean对象

 * @param str

 * @param T 

 * @return

 public static T T stringToBean(String str, Class T clazz) {

 if(str == null || str.length() = 0 || clazz == null) {

 return null;

 if(clazz == int.class || clazz == Integer.class) {

 return (T)Integer.valueOf(str);

 }else if(clazz == String.class) {

 return (T)str;

 }else if(clazz == long.class || clazz == Long.class) {

 return (T)Long.valueOf(str);

 }else {

 return JSON.toJavaObject(JSON.parseObject(str), clazz);

}

其中get方法使用连接池中的客户端实例,set方法用到的是非连接池的实例,以区分两种不同的使用方式

封装好的Redis的操作工具类后,我们就可以直接使用该工具类来进行对Redis的各种操作 。如下,直接注入即可。


@RestController

public class TestController {

 @Autowired

 private RedisService redisService;

 ......

}

到此这篇关于Spring Boot 项目集成Redis的文章就介绍到这了,更多相关Spring Boot 项目集成Redis内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


我想要获取技术服务或软件
服务范围:MySQL、ORACLE、SQLSERVER、MongoDB、PostgreSQL 、程序问题
服务方式:远程服务、电话支持、现场服务,沟通指定方式服务
技术标签:数据恢复、安装配置、数据迁移、集群容灾、异常处理、其它问题

本站部分文章参考或来源于网络,如有侵权请联系站长。
数据库远程运维 Spring Boot 项目集成Redis的方式详解