美文网首页
Springboot整合redis

Springboot整合redis

作者: 吕小凯 | 来源:发表于2020-01-20 19:56 被阅读0次

1.导入依赖

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

2.配置redis组件

package com.example.demo.xk.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
public class RedisConfig {

    @Bean(name = "redisTemplate")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, String> template = new RedisTemplate<>();
    template.setConnectionFactory(factory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
    template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
    template.afterPropertiesSet();
    return template;
    }
}

3.配置连接信息

server.port=8082

edit by lvxk 2020/01/20

Redis数据库索引(默认为0)

spring.redis.database=0  
# Redis服务器地址  
spring.redis.host=152.136.27.48
# Redis服务器连接端口  
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)  
spring.redis.password=
## 连接池最大连接数(使用负值表示没有限制)  
#spring.redis.jedis.pool.max-active=200  
## 连接池最大阻塞等待时间(使用负值表示没有限制)  
#spring.redis.jedis.pool.max-wait=-1  
## 连接池中的最大空闲连接  
#spring.redis.jedis.pool.max-idle=10 
## 连接池中的最小空闲连接  
#spring.redis.jedis.pool.min-idle=0  
# 连接超时时间(毫秒)  
spring.redis.timeout=5000

4.测试使用

package com.example.demo.xk.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisController {
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    @GetMapping(value = "set")
    public Object testRedisSet() {
     redisTemplate.opsForValue().set("name","lvxiaokai");
        return "set successfully";
    }
    
    @GetMapping(value = "get")
    public Object testRedisGet() {
     return redisTemplate.opsForValue().get("name");
    }

}

ok

相关文章

网友评论

      本文标题:Springboot整合redis

      本文链接:https://www.haomeiwen.com/subject/proezctx.html