Loading

SpringBoot集成redis简要

本文为redis服务的独立部署,内置到应用服务中同理,仅需要2、3、4三步(根据情况添加)

大致步骤:

  1. 安装redis
  2. 配置yml和添加pom
  3. 添加config配置类
  4. 添加redis数据的get、set类

详细步骤:

1、redis的安装

本人很懒,不想写安装,请移步其他道友:

https://www.cnblogs.com/wmy666/p/15148686.html

https://www.runoob.com/redis/redis-install.html

2、新建module作为redis的服务

​ application主类不想改可以不动

  • 配置yml:

    spring:
    	#应用名称
        application:
            name: redis-server
        redis:
        	#redis 数据库的数量
            database: 0
            #redis端口地址默认是6379(如果没有改redis软件的配置文件的话)
            host: 127.0.0.1
            port: 6379
            password:
            jedis:
                pool:
                	#最大连接数,设置为0则无限制
                    max-active: 8
                    #最大等待毫秒数, 单位为 ms, 超过时间会出错误信息
                    max-wait: 1
                    #空闲连接数,没有数据库的连接时依然可以保持连接不清除的个数
                    max-idle: 9
                    min-idle: 0
            #单位秒,默认为0(永不断开),在timeout时间之后一直没有连接的话断开连接
            timeout: 0
    #服务端口
    server:
        port: 8911
    
    #注册中心地址
    eureka:
        client:
            service-url:
                defaultZone: http://localhost:8900/eureka/
    
  • 更改pom

      <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
                <version>3.1.0</version>
            </dependency>
            <!--    redis  除了这个其他都是独立部署需要的  -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
        </dependencies>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>2021.0.0</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
3、添加config配置类
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;


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

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Autowired
    CacheProperties cacheProperties;

    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
        configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer()));
        return configuration;
    }


    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setValueSerializer(jsonSerializer());
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    /**
    	使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
    	否则,使用put(Object, Object)存入redis时,
    	redis中的key会变成类似于\xac\xed\x00\x05t\x00\x1IAMAKEY的结构
    **/
    private Jackson2JsonRedisSerializer jsonSerializer() {
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
        serializer.setObjectMapper(mapper);
        return serializer;
    }
}
4、缓存的get、set
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class RedisService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Resource(name="stringRedisTemplate")
    ValueOperations<String, String> valueOptStr;

    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    @Resource(name = "redisTemplate")
    ValueOperations<Object, Object> valueOptObj;

    /**
     * 根据key获取String
     * @param key
     * @return
     */
    public String getStr(String key){
        return valueOptStr.get(key);
    }

    public void setStr(String key, String val){
        valueOptStr.set(key, val);
    }

    public void del(String key){
        stringRedisTemplate.delete(key);
    }


    /**
     * Object 设置缓存
     * @param key
     * @return
     */
    public Object getObj(Object key){
        return valueOptObj.get(key);
    }

    public void setObj(Object key, Object val){
        valueOptObj.set(key, val);
    }

    public void del(Object key){
        redisTemplate.delete(key);
    }
}

调用示例:

1、集成在工程服务中的调用

@Autowired
RedisService redisService;

public String getName(String key){
    return redisService.getStr(key);
}

2、redis独立部署的调用

需要有一个controller类接收外部请求,并在调用服务那一方(消费者)添加feignclient

详见:SpringBoot集成SpringCloud简要 详细步骤 3

posted @ 2022-03-14 13:40  醉千灯  阅读(53)  评论(0编辑  收藏  举报