snake107

redis实战

springboot整合jedis访问Redis

jedis是类似于jdbc数据库连接的Redis客户端

POM.xml
 <!-- jedis -->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.8.2</version>
    </dependency>
application.yml
spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
CacheServiceImpl
@Service
public class CacheServiceImpl implements CacheService {

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private int redisPort;

    @Override
    public void setCache(String key, String value) {
        Jedis jedis = new Jedis(redisHost,redisPort);
        jedis.set(key,value);
        jedis.close();
    }

    @Override
    public String getCache(String key) {
        String value = null;
        Jedis jedis = new Jedis(redisHost,redisPort);
        value = jedis.get(key);
        jedis.close();

        return value;
    }
}

测试redis访问

@Controller
public class TestController {

    @Resource
    CacheService cacheService;

    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        cacheService.setCache("test","我的第一个Redis缓存");
        System.out.println(cacheService.getCache("test"));
        return "Hello Spring boot";
    }
}

Redis连接池框架autoloadcache

POM.xml

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
    </dependency>
<!-- AutoloadCache 启动器 -->
        <dependency>
            <groupId>com.github.qiujiayu</groupId>
            <artifactId>autoload-cache-spring-boot-starter</artifactId>
            <version>6.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
<!-- apache 对象池 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

配置文件

spring:
  application:
    name: myshop
  aop:
    proxy-target-class: false
  redis:
    host: 127.0.0.1
    port: 6379
    #    cluster:
    #      max-redirects: 10
    #      nodes:
    #      - 192.168.176.128:7001
    #      - 192.168.176.128:7002
    #      - 192.168.176.129:7001
    #      - 192.168.176.129:7002
    #      - 192.168.176.130:7001
    #      - 192.168.176.130:7002
    lettuce:
      pool:
        maxActive: 2048
        maxIdle: 200
        maxWait: 1500ms
        minIdle: 20
    jedis:
      pool:
        maxActive: 2048
        maxIdle: 200
        maxWait: 1500ms
        minIdle: 20
autoload:
  cache:
    config:
      namespace: myshop
    enable: true
    proxy-target-class: true

Java配置类

package com.suoron.springboot.config;

import com.jarvis.cache.redis.AbstractRedisCacheManager;
import com.jarvis.cache.redis.LettuceRedisClusterCacheManager;
import com.jarvis.cache.serializer.ISerializer;
import com.jarvis.cache.serializer.JacksonJsonSerializer;
import io.lettuce.core.cluster.RedisClusterClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.jarvis.cache.ICacheManager;
import com.jarvis.cache.autoconfigure.AutoloadCacheProperties;
import com.jarvis.cache.clone.ICloner;
import com.jarvis.cache.map.MapCacheManager;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.lettuce.LettuceClusterConnection;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Field;

/**
 * 为了方便测试,使用Map缓存
 *
 * @author: jiayu.qiu
 */
@Configuration
public class AutoloadCacheConfiguration {

    // @Bean
    public ICacheManager mapCacheManager(AutoloadCacheProperties config, ICloner cloner) {
        return new MapCacheManager(config.getConfig(), cloner);
    }
    @Bean
    public ISerializer<Object> autoloadCacheSerializer() {
        return new JacksonJsonSerializer();
    }
    private static final Logger LOG = LoggerFactory.getLogger(AutoloadCacheConfiguration.class);

    @Bean
    public ICacheManager mapCacheManager(AutoloadCacheProperties config, ISerializer<Object> serializer,
                                         ApplicationContext applicationContext) {
        LettuceConnectionFactory connectionFactory = null;
        try {
            connectionFactory = applicationContext.getBean(LettuceConnectionFactory.class);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        if (null == connectionFactory) {
            return null;
        }

        RedisConnection redisConnection = null;
        try {
            redisConnection = connectionFactory.getConnection(); // 当Redis配置不正确时,此处会抛异常
        } catch (Throwable e) {
            LOG.error(e.getMessage(), e);
        }
        if (null != redisConnection) {
            SpringLettuceCacheManager manager = new SpringLettuceCacheManager((LettuceConnectionFactory) connectionFactory, serializer);
            LOG.debug("ICacheManager with SpringLettuceCacheManager auto-configured," + config.getConfig());
            return manager;
        }
        return null;
    }
}
管理类SpringLettuceCacheManager
package com.suoron.springboot.config;

import com.jarvis.cache.redis.AbstractRedisCacheManager;
import com.jarvis.cache.redis.IRedis;
import com.jarvis.cache.serializer.ISerializer;
import io.lettuce.core.api.async.RedisAsyncCommands;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisConnectionUtils;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

/**
 * @author xuezhijian
 * @date 2018/6/19 上午11:03
 * @description
 */

public class SpringLettuceCacheManager extends AbstractRedisCacheManager {

    private LettuceConnectionFactory redisConnectionFactory;

    public SpringLettuceCacheManager(LettuceConnectionFactory redisConnectionFactory,ISerializer<Object> serializer) {
        super(serializer);
        this.redisConnectionFactory = redisConnectionFactory;
    }

    public LettuceConnectionFactory getRedisConnectionFactory() {
        return redisConnectionFactory;
    }


    @Override
    protected IRedis getRedis(String cacheKey) {
        return new LettuceConnectionClient(redisConnectionFactory);
    }

    public static class LettuceConnectionClient implements IRedis {
        private final LettuceConnectionFactory redisConnectionFactory;
        private final RedisConnection redisConnection;
        private final RedisAsyncCommands<byte[],byte[]> commands;

        public LettuceConnectionClient(LettuceConnectionFactory redisConnectionFactory) {
            this.redisConnectionFactory = redisConnectionFactory;
            this.redisConnection = RedisConnectionUtils.getConnection(redisConnectionFactory);
            this.commands = (RedisAsyncCommands) redisConnection.getNativeConnection();
        }

        @Override
        public void close() throws IOException {
            RedisConnectionUtils.releaseConnection(redisConnection, redisConnectionFactory);
        }

        @Override
        public void set(byte[] key, byte[] value) {
            commands.set(key, value);
        }

        @Override
        public void setex(byte[] key, int seconds, byte[] value) {
            commands.setex(key, seconds, value);
        }

        @Override
        public void hset(byte[] key, byte[] field, byte[] value) {
            commands.hset(key, field, value);
        }

        @Override
        public void hset(byte[] key, byte[] field, byte[] value, int seconds) {
            commands.hset(key, field, value);
            commands.expire(key, seconds);
        }

        @Override
        public byte[] get(byte[] key) {
            try {
                return commands.get(key).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public byte[] hget(byte[] key, byte[] field) {
            try {
                return commands.hget(key, field).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public void del(byte[] key) {
            commands.del(key);
        }

        @Override
        public void hdel(byte[] key, byte[]... fields) {
            commands.hdel(key, fields);
        }
    }

}

测试

    @Override
    @Cache(expire=600,expireExpression="null == #retVal ? 1:600",key="'SESSION_' + #args[0]",autoload=true)
    public UserSessionEntiy userLogin(String username, String password) {
        //TODO 去数据库中获取账号密码
        UserSessionEntiy userSessionEntiy = new UserSessionEntiy();
        userSessionEntiy.setUsername(username);
        userSessionEntiy.setPhone("13112345678");

        return userSessionEntiy;
    }

访问URL: http://localhost:8080/autoload-cache-ui.html

posted @ 2019-11-26 22:30  爱喝奶茶的皮卡丘  阅读(184)  评论(0编辑  收藏  举报