Spring-boot + redis + jedisPool

简单的配置Speing-boot + redis

pom文件:


		
			org.springframework.boot
			spring-boot-starter-redis
			RELEASE
		

		
			com.alibaba
			fastjson
			1.2.38
		

配置文件:

#redis配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
# 连接超时时间(毫秒)
spring.redis.timeout=0
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=1
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1

加载配置类:

@Configuration
//初始化jedisPool
public class RedisConfig {
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory){
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }
}

实际操作类:

@Repository
public class UserRedis{
    @Autowired
    private RedisTemplate redisTemplate;

    public void add(String key,Long time,User user){
        redisTemplate.opsForValue().set(key, JSONObject.toJSONString(user),time, TimeUnit.MINUTES);
    }

    public User get(String key){
        User user = null;
        String userJson = redisTemplate.opsForValue().get(key);
        if(!StringUtils.isEmpty(userJson)){
            user = JSONObject.parseObject(userJson,User.class);

        }
        return user;
    }

    public List getList(String key){
        List ts = null;
        String listJson = redisTemplate.opsForValue().get(key);
        if(!StringUtils.isEmpty(listJson)){
            ts = JSONObject.parseArray(listJson,User.class);
        }
        return ts;
    }

    public void delete(String key){
        redisTemplate.opsForValue().getOperations().delete(key);
    }

}

测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {

    private Logger logger = LoggerFactory.getLogger(RedisTest.class);
    @Autowired
    private UserRedis userRedis;
    @Test
    public void addOneUser(){
        User user = new User();
        user.setUserName("wzl");
        user.setPassword("wzl");
        userRedis.add(User.class.getName() + ":userByname:" + user.getUserName(),10L,user);
    }
}

这样就ok了

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(知识总结)