SpringBoot整合redis

本文详细介绍了SpringBoot如何整合Redis,包括配置文件解析、自动装配类的分析,以及如何在应用中使用redisTemplate进行操作。通过示例展示了配置redis的IP和端口,并进行了单元测试验证。
摘要由CSDN通过智能技术生成

文章目录

原创不易,未经允许,请勿转载。

博客主页:https://xiaojujiang.blog.csdn.net/

SpringBoot:2.1.6.RELEASE

redis:3.2.11

springboot内部已经帮我们整理好了配置redis所需要的依赖。我们只需要映入对应的starter即可。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

在进行配置之前,我们先来看下springboot为我们准备好了哪些配置。

下面代码省略了一些getter和setter。

首先我们可以看到这个配置文件,与spring.redis开头绑定。我们之后要对配置进行修改的话,就只要在yaml或者properties配置文件中进行修改即可。例如spring.redis.database=xxxxx

在这配置文件中可以看到,定义了许多的属性,有url、host、password之类的。

RedisProperties

@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {

	/**
	 * Database index used by the connection factory.
	 */
	private int database = 0;

	/**
	 * Connection URL. Overrides host, port, and password. User is ignored. Example:
	 * redis://user:password@example.com:6379
	 */
	private String url;

	/**
	 * Redis server host.
	 */
	private String host = "localhost";

	/**
	 * Login password of the redis server.
	 */
	private String password;

	/**
	 * Redis server port.
	 */
	private int port = 6379;

	/**
	 * Whether to enable SSL support.
	 */
	private boolean ssl;

	/**
	 * Connection timeout.
	 */
	private Duration timeout;

	private Sentinel sentinel;

	private Cluster cluster;

	private final Jedis jedis = new Jedis();

	private final Lettuce lettuce = new Lettuce();

	/**
	 * Pool properties.
	 */
	public static class Pool {

		/**
		 * Maximum number of "idle" connections in the pool. Use a negative value to
		 * indicate an unlimited number of idle connections.
		 */
		private int maxIdle = 8;

		/**
		 * Target for the minimum number of idle connections to maintain in the pool. This
		 * setting only has an effect if both it and time between eviction runs are
		 * positive.
		 */
		private int minIdle = 0;

		/**
		 * Maximum number of connections that can be allocated by the pool at a given
		 * time. Use a negative value for no limit.
		 */
		private int maxActive = 8;

		/**
		 * Maximum amount of time a connection allocation should block before throwing an
		 * exception when the pool is exhausted. Use a negative value to block
		 * indefinitely.
		 */
		private Duration maxWait = Duration.ofMillis(-1);

		/**
		 * Time between runs of the idle object evictor thread. When positive, the idle
		 * object evictor thread starts, otherwise no idle object eviction is performed.
		 */
		private Duration timeBetweenEvictionRuns;

	}

	/**
	 * Cluster properties.
	 */
	public static class Cluster {

		/**
		 * Comma-separated list of "host:port" pairs to bootstrap from. This represents an
		 * "initial" list of cluster nodes and is required to have at least one entry.
		 */
		private List<String> nodes;

		/**
		 * Maximum number of redirects to follow when executing commands across the
		 * cluster.
		 */
		private Integer maxRedirects;

	}

	/**
	 * Redis sentinel properties.
	 */
	public static class Sentinel {

		/**
		 * Name of the Redis server.
		 */
		private String master;

		/**
		 * Comma-separated list of "host:port" pairs.
		 */
		private List<String> nodes

	}

	/**
	 * Jedis client properties.
	 */
	public static class Jedis {
		/**
		 * Jedis pool configuration.
		 */
		private Pool pool;
	}

	/**
	 * Lettuce client properties.
	 */
	public static class Lettuce {
		/**
		 * Shutdown timeout.
		 */
		private Duration shutdownTimeout = Duration.ofMillis(100);

		/**
		 * Lettuce pool configuration.
		 */
		private Pool pool;
	}
}

看完配置文件,接下来我们来看看redis的自动装配类。

可以看到,在这个autoconfiguration里面,会往容器中注册两个bean,一个是redisTemplate,一个是stringRedisTemplate。前提是,容器中不存在这两个bean实例@ConditionalOnMissingBean

RedisAutoConfiguration

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean(name = "redisTemplate")
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
			throws UnknownHostException {
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}

	@Bean
	@ConditionalOnMissingBean
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)
			throws UnknownHostException {
		StringRedisTemplate template = new StringRedisTemplate();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}

}

可以看到,在创建redisTemplate的时候,方法需要传入一个连接工厂,那这个工厂是从哪里来的呢?

RedisAutoConfiguration上有这两个注解,显然连接工厂就是从这里获取的。

@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })

LettuceConnectionConfiguration

@Configuration
@ConditionalOnClass(RedisClient.class)
class LettuceConnectionConfiguration extends RedisConnectionConfiguration {
	@Bean
	@ConditionalOnMissingBean(RedisConnectionFactory.class)
	public LettuceConnectionFactory redisConnectionFactory(ClientResources clientResources)
			throws UnknownHostException {
		LettuceClientConfiguration clientConfig = getLettuceClientConfiguration(clientResources,
				this.properties.getLettuce().getPool());
		return createLettuceConnectionFactory(clientConfig);
	}
}

JedisConnectionConfiguration

@Configuration
@ConditionalOnClass({ GenericObjectPool.class, JedisConnection.class, Jedis.class })
class JedisConnectionConfiguration extends RedisConnectionConfiguration {
	@Bean
	@ConditionalOnMissingBean(RedisConnectionFactory.class)
	public JedisConnectionFactory redisConnectionFactory() throws UnknownHostException {
		return createJedisConnectionFactory();
	}
}

在springboot中默认导入了lettuce的依赖。如果需要使用jedis的话,可以在pom中排除lettuce的依赖,然后导入入jedis即可。

顺带提一下,在之后版本的springboot中,可以使用spring.reids.client-type=xxx这个配置指定使用jedis还是lettuce。当然也要引入对应的依赖。

说了这么多,现在开始来动手实验一下吧。

首先启动一个redis服务器,这里就不演示了。

application.yml

配置redis的ip和使用的端口。

spring:
  redis:
    port: 6379
    host: localhost

接下来就可以进行单元测试看看了

自动注入redisTemplate。

@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringbootRedisApplicationTests {

    @Autowired
    private RedisTemplate<String,String> template;

    @Test
    public void contextLoads() {
//        template.opsForValue().set("jxj","jxj");
               
        // 这些以ops方法开头的,返回的是操作redis对应数据结构的
       // template.opsForValue();
       // template.opsForZSet();
       // template.opsForGeo();
       // template.opsForHash();
       // template.opsForHyperLogLog();
       // template.opsForList();
    }

}

执行完之后,可以查看下redis中是否多了对应的key。

拒绝白嫖从一键三连开始!

原创不易,未经允许,请勿转载。

博客主页:https://xiaojujiang.blog.csdn.net/

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jiangxiaoju

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值