SpringBoot整合redis

Posted jiangxiaoju

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot整合redis相关的知识,希望对你有一定的参考价值。

文章目录

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

博客主页: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/

以上是关于SpringBoot整合redis的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot的整合(整合redis)

springboot+shiro+redis(单机redis版)整合教程-续(添加动态角色权限控制)

SpringBoot系列十:SpringBoot整合Redis

SpringBoot整合Redis

springboot整合jedis

SpringBoot整合Redis