Springboot3.1.x integrates Redis to avoid pitfalls

Integrated Jar package

First introduce the dependent jar package of Spring Data Redis:

<!-- Redis缓存依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Client connection test (normal)

Then write the test Redis connection code:

/**
* 测试Redis连接
*/
@Test
void redisConnectTest(){
	// 使用RedisClient测试连接
	RedisClient redisClient  = RedisClient
			.create(RedisURI.Builder
					.redis("192.168.1.121",6379)
					.withPassword("000000".toCharArray())
					.withDatabase(14)
					.build());
	redisClient.setOptions(ClientOptions.builder().protocolVersion(ProtocolVersion.RESP2).build());
	RedisCommands<String, String> command = redisClient.connect().sync();
	command.set("hw","Hello World");
	System.out.println(command.get("hw"));

}

Results of the:

It means the connection with the database is normal.

Automatic injection of connection test (wrong password)

Now write the database connection information into the configuration file and test the connection through automatic injection (you can change the configuration file later when the project goes online).

Configuration file:

spring:
  data:
    redis:
      # Redis服务器地址
      host: 192.168.1.121
      # Redis服务器端口
      port: 6379
      # Redis连接密码
      password: 000000
      # 使用的Redis数据库索引号
      database: 14
      # Redis数据读取超时时间
      timeout: 5000

Write test Redis connection code:

@Autowired
RedisTemplate redisTemplate;

/**
 * 测试Redis连接
 */
@Test
void redisConnectTest(){
	// 使用自动注入方式测试连接
	redisTemplate.opsForValue().set("a",1);
	System.out.println(redisTemplate.opsForValue().get("a"));
}

Execution results (prompt password error):

After repeated checking, there is no problem with the password. After debugging, it was found that the obtained configuration information password only has one character "0" (char[1]), but the configuration file clearly contains 6 zeros.

Then modify the configuration file (add double quotes to the password):

spring:
  data:
    redis:
      # Redis服务器地址
      host: 192.168.1.121
      # Redis服务器端口
      port: 6379
      # Redis连接密码
      password: "000000"
      # 使用的Redis数据库索引号
      database: 14
      # Redis数据读取超时时间
      timeout: 5000

Executed again and found that it was normal:

It seems that the value of the configuration file will be converted automatically. I hope this article will be helpful to you (I wasted a whole morning on this pit...)

Guess you like

Origin blog.csdn.net/Asgard_Hu/article/details/132622753