Springboot integrates with Redis

SpringBoot operation data: Spring-data jpa jdbc mongodb redis!
SpringData is also a project as famous as SpringBoot!
Note: After SpringBoot2
. BIO mode
lettuce: Using netty, instances can be shared among multiple threads, there is no thread insecurity, thread data can be reduced, and NIO mode is more preferred

Integration steps

Introduce dependencies

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

Insert image description here

 @Bean
    @ConditionalOnMissingBean(
        name = {"redisTemplate"}
    )  
    我们可以自定义RedisTemplate
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
    // 使用默认的RedisTemplate 没有过多的设置,但是我们实际当中一般都需要进行序列化
    //<Object, Object> 需要强转 <String, Object>
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    // 由于String类型是Redis经常使用的类型所以这个地方单独写了一个StringRedisTemplate 
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

Configuration related information

Insert image description here
You can configure it according to the actual situation

test

 */
@RestController
public class HelloController {

    @Resource
    private RedisTemplate redisTemplate;
    @RequestMapping("hello")
    public String hell(){
        redisTemplate.opsForValue().set("javakey","ddd");
        Object javakey = redisTemplate.opsForValue().get("javakey");
        System.out.printf(javakey.toString());
        redisTemplate.opsForValue().set("中文","我也是中文");
        System.out.println(redisTemplate.opsForValue().get("中文").toString());
        return "hello";
    }
}

Guess you like

Origin blog.csdn.net/wufagang/article/details/109633455