springboot工程集成redis缓存

一,Linux安装Redis

安装Redis的过程就不多说了,参考之前的文章即可。

https://www.cnblogs.com/fantongxue/p/12443575.html

二,Springboot工程集成Redis

1,加入springboot-redis依赖包

首先要新建一个springboot工程,然后加入整合Redis的依赖包

	 <!--集成redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.4.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

2,Redis配置(application.yml)

然后在application.yml配置中加入Redis的配置。

前提是必须在Linux服务器的Redis环境全部配置好,至于Redis配置的注意事项下面一会儿会说到。连接端口和连接密码是在redis.conf配置文件中修改的。

spring:
  redis:
    host: 101.201.101.206 #redis主机ip
    port: 6379 #redis端口
    password:  #redis连接密码,默认为空

其实Redis的配置挺多的,但是这里只是演示,原谅作者有点儿懒!

3,RedisConfig配置类

package com.aaa.demo.config;

import java.lang.reflect.Method;
import org.springframework.beans.factory.annotation.Value;
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.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    
    

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;

    @Bean
    public KeyGenerator wiselyKeyGenerator(){
    
    
        return new KeyGenerator() {
    
    
            @Override
            public Object generate(Object target, Method method, Object... params) {
    
    
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
    
    
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
    
    
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(host);
        factory.setPort(port);
        factory.setPassword(password);
//        factory.getPoolConfig().setMaxIdle(maxIdle);
//        factory.getPoolConfig().setMaxTotal(maxActive);
        return factory;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
    
    
        RedisCacheManager cacheManager =RedisCacheManager.create(factory);
        // Number of seconds before expiration. Defaults to unlimited (0)
//        cacheManager.setDefaultExpiration(10); //设置key-value超时时间
        return cacheManager;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
    
    
        StringRedisTemplate template = new StringRedisTemplate(factory);
        setSerializer(template); //设置序列化工具,这样ReportBean不需要实现Serializable接口
        template.afterPropertiesSet();
        return template;
    }

    private void setSerializer(StringRedisTemplate template) {
    
    
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
    }
}

4,RedisUtils工具类

该工具类注入了RedisTemplate,也就是Redis的操作类,然后使用该操作类进行缓存的增删改查操作并封装了方法,然后有了下面这个无敌的RedisUtils工具类,只要调用该类的方法传参就可以任性的操作Redis数据库了。

package com.aaa.demo.util;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service
public class RedisUtils {
    
    
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 写入缓存
     */
    public boolean set(final String key, Object value) {
    
    
        boolean result = false;
        try {
    
    
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 写入缓存设置时效时间
     */
    public boolean set(final String key, Object value, Long expireTime , TimeUnit timeUnit) {
    
    
        boolean result = false;
        try {
    
    
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 批量删除对应的value
     */
    public void remove(final String... keys) {
    
    
        for (String key : keys) {
    
    
            remove(key);
        }
    }
    /**
     * 批量删除key
     */
    public void removePattern(final String pattern) {
    
    
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0){
    
    
            redisTemplate.delete(keys);
        }
    }
    /**
     * 删除对应的value
     */
    public void remove(final String key) {
    
    
        if (exists(key)) {
    
    
            redisTemplate.delete(key);
        }
    }
    /**
     * 判断缓存中是否有对应的value
     */
    public boolean exists(final String key) {
    
    
        return redisTemplate.hasKey(key);
    }
    /**
     * 读取缓存
     */
    public Object get(final String key) {
    
    
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
    /**
     * 哈希 添加
     */
    public void hmSet(String key, Object hashKey, Object value){
    
    
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put(key,hashKey,value);
    }
    /**
     * 哈希获取数据
     */
    public Object hmGet(String key, Object hashKey){
    
    
        HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
        return hash.get(key,hashKey);
    }
    /**
     * 列表添加
     */
    public void lPush(String k,Object v){
    
    
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k,v);
    }
    /**
     * 列表获取
     */
    public List<Object> lRange(String k, long l, long l1){
    
    
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k,l,l1);
    }
    /**
     * 集合添加
     */
    public void add(String key,Object value){
    
    
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key,value);
    }
    /**
     * 集合获取
     */
    public Set<Object> setMembers(String key){
    
    
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }
    /**
     * 有序集合添加
     */
    public void zAdd(String key,Object value,double scoure){
    
    
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key,value,scoure);
    }
    /**
     * 有序集合获取
     */
    public Set<Object> rangeByScore(String key,double scoure,double scoure1){
    
    
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }
}

5,写测试类进行测试

第一次请求该方法,如果该缓存不存在,然后去mysql获取数据,并存入redis,最后返回结果;

第二次请求该方法,如果缓存存在,直接从缓存中获取数据,最后返回结果。(不经过数据库了)

@RestController
public class RedisController {
    
    

    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping("/testRedis")
    public String testRedis(){
    
    
        String id="1";
        //查询redis缓存中是否存在
        boolean exists = redisUtils.exists(id);
        if(exists){
    
    
            //获取缓存
            Object obj = redisUtils.get(id);
            System.out.println("从缓存中获取的数据:"+obj.toString());
            return obj.toString();
        }else{
    
    
            System.out.println("模拟去mysql获取数据");
            String list="test data!";
            //数据插入缓存
            //数据插入缓存(set中的参数含义:key值,user对象,缓存存在时间10(long类型),时间单位)
            redisUtils.set(id,list,10L, TimeUnit.MINUTES);
            System.out.println("数据已存入redis");
            return list;
        }
    }
}

Redis安装声明:

Linux环境安装好Redis并启动Redis之后,在springboot工程启动后报错,表示Redis处于保护状态,外部网络不能连接,所以要去配置redis.conf配置文件。

注释掉绑定ip

bind 127.0.0.1

Redis默认不是以守护进程的方式运行,可以通过该配置项修改,使用yes启用守护进程,设置为no
daemonize no

保护模式,关闭保护模式,否则外部ip无法连接
protected-mode no

配置完之后重启Redis,注意的是,一定要Redis和配置文件redis.conf一起启动,否则配置文件不会起作用。

./redis-server redis.conf

这样就可以连接了!

猜你喜欢

转载自blog.csdn.net/weixin_44001965/article/details/105293578