springboot2.X整合redis

SpringBoot2之后,默认采用Lettuce作为redis的连接客户端

配置文件application参考官方文档

https://docs.spring.io/spring-boot/docs/2.1.4.RELEASE/reference/htmlsingle/

# REDIS (RedisProperties)
spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing commands across the cluster.
spring.redis.cluster.nodes= # Comma-separated list of "host:port" pairs to bootstrap from.
spring.redis.database=0 # Database index used by the connection factory.
spring.redis.url= # Connection URL. Overrides host, port, and password. User is ignored. Example: redis://user:password@example.com:6379
spring.redis.host=localhost # Redis server host.
spring.redis.jedis.pool.max-active=8 # Maximum number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.jedis.pool.max-idle=8 # Maximum number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.jedis.pool.max-wait=-1ms # 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.
spring.redis.jedis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
spring.redis.lettuce.pool.max-active=8 # Maximum number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.lettuce.pool.max-idle=8 # Maximum number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.lettuce.pool.max-wait=-1ms # 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.
spring.redis.lettuce.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
spring.redis.lettuce.shutdown-timeout=100ms # Shutdown timeout.
spring.redis.password= # Login password of the redis server.
spring.redis.port=6379 # Redis server port.
spring.redis.sentinel.master= # Name of the Redis server.
spring.redis.sentinel.nodes= # Comma-separated list of "host:port" pairs.
spring.redis.ssl=false # Whether to enable SSL support.
spring.redis.timeout= # Connection timeout.

如果使用lettuce连接客户端

依赖为

<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

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

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

如果使用jedis连接客户端

添加依赖

<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-pool2</artifactId>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

配置文件

spring:
  redis:
    database: 0
    host: 192.168.25.201
    port: 6379
    password: 
    jedis: 
      pool:
        max-idle: 10
        max-active: 10
        max-wait: -1
        min-idle: 0

配置类

@Configuration
public class RedisAutoConfig {
	@Bean
    public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPool,
            RedisStandaloneConfiguration jedisConfig) {
        JedisConnectionFactory connectionFactory = new JedisConnectionFactory(jedisConfig);
        connectionFactory.setPoolConfig(jedisPool);
        return connectionFactory;
    }
	
	 @Configuration
	    public static class JedisConf {
	        @Value("${spring.redis.host}")
	        private String host;
	        @Value("${spring.redis.port}")
	        private Integer port;
	        @Value("${spring.redis.password}")
	        private String password;
	        @Value("${spring.redis.database}")
	        private Integer database;

	        @Value("${spring.redis.jedis.pool.max-active}")
	        private Integer maxActive;
	        @Value("${spring.redis.jedis.pool.max-idle}")
	        private Integer maxIdle;
	        @Value("${spring.redis.jedis.pool.max-wait}")
	        private Long maxWait;
	        @Value("${spring.redis.jedis.pool.min-idle}")
	        private Integer minIdle;

	        @Bean
	        public JedisPoolConfig jedisPool() {
	            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
	            jedisPoolConfig.setMaxIdle(maxIdle);
	            jedisPoolConfig.setMaxWaitMillis(maxWait);
	            jedisPoolConfig.setMaxTotal(maxActive);
	            jedisPoolConfig.setMinIdle(minIdle);
	            return jedisPoolConfig;
	        }

	        @Bean
	        public RedisStandaloneConfiguration jedisConfig() {
	            RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
	            config.setHostName(host);
	            config.setPort(port);
	            config.setDatabase(database);
	            config.setPassword(RedisPassword.of(password));
	            return config;
	        }
	    }
}

测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApiRepeatApplicationTests {
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Test
	public void add(){
		stringRedisTemplate.opsForValue().set("test02","123");
	}
	@Test
	public void get(){
		String testValue = stringRedisTemplate.opsForValue().get("test01");
		System.out.println("test01存放有"+testValue);
	}
	@Test
	public void del(){
		stringRedisTemplate.delete("test01");
	}
	@Test
	public void expire(){
		stringRedisTemplate.opsForValue().set("expire", "123");
		String testValue = stringRedisTemplate.opsForValue().get("expire");
		System.out.println("expire存放有"+testValue);
		stringRedisTemplate.expire("expire", 5,TimeUnit.SECONDS);
		Long expireTime = stringRedisTemplate.getExpire("expire");
		System.out.println("expireTime:"+expireTime);
	}
	
	
	public void setString(String key, Object data, Long timeout) {
		if (data instanceof String) {
			String value = (String) data;
			stringRedisTemplate.opsForValue().set(key, value);
		}
		if (timeout != null) {
			stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
		}
	}

	public Object getString(String key) {
		return stringRedisTemplate.opsForValue().get(key);
	}

	public void delKey(String key) {
		stringRedisTemplate.delete(key);
	}

}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值