springboot2使用lettuce操作redis

srpingboot2升级之后,使用lettuce连接redis,不在使用jedis
写个例子,试验一下。
首先在application.properties里面添加redis配置信息

spring.redis.host=127.0.0.1
#spring.redis.password= 
spring.redis.port= 6379
spring.redis.timeout=1000
spring.redis.database=0
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.max-active=8 

注意。之前的配置方式是这样的

    spring.redis.pool.max-wait=-1
	spring.redis.pool.max-idle=8
   spring.redis.pool.min-idle=0

配置中间添加了lettuce.pool
然后添加一个工具类,进行序列化操作

import java.io.Serializable;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheAutoConfiguration {
	@Bean
    public RedisTemplate redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

创建一个controller,来实现是否存储

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController{
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisCacheTemplate;
    
    @RequestMapping(value = "/alluser",method = RequestMethod.GET)
    public String getallusers(Model model) {
       stringRedisTemplate.opsForValue().set("keytest", "cuiyw");
       final String keytest = stringRedisTemplate.opsForValue().get("keytest");
       model.addAttribute("keytest", keytest);
       String key = "1857XXXX040";
       redisCacheTemplate.opsForValue().set(key, "wusnan");
       // TODO 对应 String(字符串)
       return "userlist";
    }
}

最后打开redis服务器,启动springboot项目。访问地址,redis客户端可以读取数据。

你可能感兴趣的:(配置)