springboot集成redis(用jedis连接池)

pom.xml中添加(默认是用lettuce,想用jedis需要排除掉lettuce):

<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-data-redisartifactId>
	<exclusions>
		<exclusion>
			<groupId>io.lettucegroupId>
			<artifactId>lettuce-coreartifactId>
		exclusion>
	exclusions>
dependency>
<dependency>
	<groupId>redis.clientsgroupId>
	<artifactId>jedisartifactId>
dependency>

application.properties中添加:

spring.redis.database=0
spring.redis.host=47.104.176.200
spring.redis.port=6379
spring.redis.password=1234
#很多人这里都写0
spring.redis.timeout=3000

# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=50
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=50
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=5

**为什么不是spring.redis.pool.max-active **
因为新版本的RedisProperties类把Pool放到Redis中了。
有2个可选的连接池,redislettuce,如果用lettuce,那么写为spring.redis.lettuce.pool.max-active

使用RedisTemplate会乱码,因为redis存取的时候会用byte的形式。
解决方法:用StringRedisTemplate,它默认使用utf-8编码。

LoginController代码:

@RestController
@RequestMapping("")
public class LoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @RequestMapping("/login")
    public String login(HttpServletRequest request){
        System.out.println(stringRedisTemplate);
        ValueOperations valueOperations = stringRedisTemplate.opsForValue();

        valueOperations.set("shanghai","shanghai"); // 新增
        valueOperations.set("hebei","shijiazhuang2"); // 存在的话就是修改
        stringRedisTemplate.delete("one"); // del
        return "fail";
    }
}

debug模式启动,浏览器输入: http://localhost:8080/login

其他

报错:Could not get a resource from the pool

毫无疑问,链接不上。
看下是host或者密码哪个不对。
有一点需要注意下,yml中的value不能有@等特殊字符,如果有,两端加上单引号可以解决问题。

spring-data-redis官网文档(很不错):
https://docs.spring.io/spring-data/redis/docs/current/reference/html/#redis:requirements

其他redis工具类的引入

<dependency>
	<groupId>com.iqarr.redisgroupId>
	<artifactId>zy-redis-utilsartifactId>
	<version>0.0.2version>
dependency>

你可能感兴趣的:(spring)