(1)添加pom依赖
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
(2)注册相关bean
package cn.coreqi.config; import cn.coreqi.entities.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration
public class RedisConfig {
// @Bean
// public RedisConnectionFactory redis(){
// RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
// redisStandaloneConfiguration.setHostName("192.168.205.128");
// redisStandaloneConfiguration.setPort(6379);
// redisStandaloneConfiguration.setDatabase(0);
// //redisStandaloneConfiguration.setPassword(RedisPassword.of("123456"));
//
// JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();
// jedisClientConfiguration.connectTimeout(Duration.ofMillis(6000));// connection timeout
//
// JedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration.build());
// return factory;
// }
@Bean
public RedisConnectionFactory redis(){
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName("192.168.205.128");
factory.setPort(6379);
return factory;
} @Bean
public RedisTemplate<String, User> redisTemplate(RedisConnectionFactory redis){
RedisTemplate<String, User> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redis);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<User>(User.class));
return redisTemplate;
} // @Bean
// public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redis){
// return new StringRedisTemplate(redis);
// }
}