spring boot -spring data-redis

//添加依赖
<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>

添加配置类,初始化RedisTemplate

@Configuration
public class ConfigurationRedis { @Bean
public JedisPoolConfig JedisPoolConfig () {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle();
jedisPoolConfig.setMinIdle();
jedisPoolConfig.setMaxTotal();
return jedisPoolConfig;
}
@Bean
public JedisConnectionFactory JedisConnectionFacoty(JedisPoolConfig jedisPoolConfig){
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
jedisConnectionFactory.setHostName("192.168.204.129");
jedisConnectionFactory.setPort();
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;
}
}

测试类

@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"));
  }
}
上一篇:Codeforces Round #324 (Div. 2) C (二分)


下一篇:Codeforces Round #404 (Div. 2)A B C二分