//添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<!-- 1.5的版本默認採用的鏈接池技術是jedis 2.0以上版本默認鏈接池是lettuce, 在這裏採用jedis,因此須要排除lettuce的jar -->
<exclusions>
<exclusion>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</exclusion>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 添加jedis客戶端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!--spring2.0集成redis所需common-pool2-->
<!-- 必須加上,jedis依賴此 -->
<!-- spring boot 2.0 的操做手冊有標註 你們能夠去看看 地址是:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>RELEASE</version>
</dependency>
添加配置類,初始化RedisTemplatehtml
@Configuration public class ConfigurationRedis { @Bean public JedisPoolConfig JedisPoolConfig () { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(10); jedisPoolConfig.setMinIdle(5); jedisPoolConfig.setMaxTotal(20); return jedisPoolConfig; } @Bean public JedisConnectionFactory JedisConnectionFacoty(JedisPoolConfig jedisPoolConfig){ JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); jedisConnectionFactory.setPoolConfig(jedisPoolConfig); jedisConnectionFactory.setHostName("192.168.204.129"); jedisConnectionFactory.setPort(6379); return jedisConnectionFactory; } @Bean public RedisTemplate<String,Object> RedisTemplate (JedisConnectionFactory jedisConnectionFactory) { RedisTemplate<String,Object> redisTemplate = new RedisTemplate<String,Object>(); redisTemplate.setConnectionFactory(jedisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new StringRedisSerializer()); return redisTemplate; } }
測試類redis
@SpringBootTest(classes = springBoot.class ) @RunWith(SpringJUnit4ClassRunner.class) public class RedisTest { @Autowired RedisTemplate<String,Object> redisTemplate ; @Test public void test1(){ redisTemplate.opsForValue().set("key1","v2我是"); redisTemplate.opsForValue().set("key1","v3我是"); System.out.println(redisTemplate.opsForValue().get("key1")); }
@Test
public void test2 () {
//RedisUser implements Serializable
RedisUser redisUser = new RedisUser(1,"呵呵",10);
this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
this.redisTemplate.opsForValue().set("user",redisUser);
System.out.println(this.redisTemplate.opsForValue().get("user"));
this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(RedisUser.class));
this.redisTemplate.opsForValue().set("user",redisUser);
System.out.println(this.redisTemplate.opsForValue().get("user"));
}
}