美文网首页程序员
SpringCloud 2.x 整合Redis 及其常用API

SpringCloud 2.x 整合Redis 及其常用API

作者: 都是自己人_ | 来源:发表于2019-03-12 12:08 被阅读0次

1、引入jar,pom配置


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

2、Redis配置,application.yml


#redis

  redis:

    host: 127.0.0.1

    port: 6379

    password:

    database: 1

    timeout: 10000 # 连接超时时间(毫秒)

    lettuce:

      pool:

        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)默认 8

        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)默认 -1

        max-idle: 8 # 连接池中的最大空闲连接默认 8

        min-idle: 0 # 连接池中的最小空闲连接默认 0

3.RedisConfig配置


package com.deploy.config;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;

import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;

import org.springframework.cache.CacheManager;

import org.springframework.cache.annotation.CachingConfigurerSupport;

import org.springframework.cache.annotation.EnableCaching;

import org.springframework.cache.interceptor.KeyGenerator;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.cache.RedisCacheManager;

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;

import javax.annotation.Resource;

import java.io.Serializable;

import java.lang.reflect.Method;

import java.util.HashSet;

import java.util.Set;

/**

* Redis缓存配置类

* @author xuc

*

*/

@Configuration

@EnableCaching

@AutoConfigureAfter(RedisAutoConfiguration.class)

public class RedisConfig extends CachingConfigurerSupport {

    public RedisConfig() {

        System.out.println("RedisConfig容器启动初始化。。。");

    }

    @Resource

    private LettuceConnectionFactory lettuceConnectionFactory;

    @Bean

    public KeyGenerator keyGenerator() {

        return new KeyGenerator() {

            @Override

            public Object generate(Object target, Method method, Object... params) {

                StringBuffer sb = new StringBuffer();

                sb.append(target.getClass().getName());

                sb.append(method.getName());

                for (Object obj : params) {

                    sb.append(obj.toString());

                }

                return sb.toString();

            }

        };

    }

    // 缓存管理器

    @Bean

    public CacheManager cacheManager() {

        RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder

                .fromConnectionFactory(lettuceConnectionFactory);

        @SuppressWarnings("serial")

        Set<String> cacheNames = new HashSet<String>() {

            {

                add("codeNameCache");

            }

        };

        builder.initialCacheNames(cacheNames);

        return builder.build();

    }

    @Bean

    public RedisTemplate<String,Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory){

        RedisTemplate<String,Serializable> template = new RedisTemplate<String,Serializable>();

        template.setKeySerializer(new StringRedisSerializer());

        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        template.setHashKeySerializer(new StringRedisSerializer());// Hash key序列化

        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());// Hash value序列化

        template.setConnectionFactory(redisConnectionFactory);

        return template;

    }

}

4、RedisTemplate 使用


    @Autowired

    private RedisTemplate<String, Serializable> redisCacheTemplate;

  @RequestMapping("test")

    public Map test(){

        Map<String,Object> result = new HashMap<>();

        result.put("code", "000000");

        result.put("msg", "success");

        User u = new User();

        u.setId("123");

        u.setState(23);

        u.setUser_photo("huangjinjin");

        u.setPosition("cto");

        result.put("body", u);

        redisCacheTemplate.opsForValue().set(String.valueOf(u.getId()), u);

        redisCacheTemplate.opsForValue().set("code",123412);

        Serializable code = redisCacheTemplate.opsForValue().get("code");

        return successList(result);

    }

5、RedisTemplate 主要API

RedisTemplate中定义了对5种数据结构操作

redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set

API参考连接

https://www.cnblogs.com/shamo89/p/8622152.html

相关文章

网友评论

    本文标题:SpringCloud 2.x 整合Redis 及其常用API

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