SpringBoot之整合Redis分析和实现-基于Spring Boot2.0.2版本

一、背景介绍

公司最近的新项目在进行技术框架升级,基于的Spring Boot的版本是2.0.2,整合Redis数据库。网上基于2.X版本的整个Redis少之又少,中间踩了不少坑,特此把整合过程记录,以供小伙伴们参考。

本文的基于在于会搭建Spring Boot项目的基础上进行的,入门是小白的话,请自行学习相关基础知识,网上或相关书籍很多。

由于我本人对Maven比较熟悉,所以是以Maven进行的。Gradle类似,核心思想都是一样的,实现项目管理工具不同而已。

二、整合过程

1.创建Spring Boot项目(2.0.2版本)

利用idea提供的接口进行创建,创建后目录结构如下:(请忽略mybatis.log4j2等相关代码和文件)
这里写图片描述

2.pom依赖

        <!-- Spring Boot Redis依赖 -->
        <!-- 注意:1.5版本的依赖和2.0的依赖不一样,注意看哦 1.5我记得名字里面应该没有“data”, 2.0必须是“spring-boot-starter-data-redis” 这个才行-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <!-- 1.5的版本默认采用的连接池技术是jedis  2.0以上版本默认连接池是lettuce, 在这里采用jedis,所以需要排除lettuce的jar -->
            <exclusions>
                <exclusion>
                    <groupId>redis.clients</groupId>
                    <artifactId>jedis</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        
        <!-- 添加jedis客户端 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

        <!--spring2.0集成redis所需common-pool2-->
        <!-- 必须加上,jedis依赖此  -->
        <!-- spring boot 2.0 的操作手册有标注 大家可以去看看 地址是:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.5.0</version>
        </dependency>

        <!-- 将作为Redis对象序列化器 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

3.yml相关Redis配置

其实关于Redis的配置主要包括两方面,一时Redis的配置,一个是jedis pool连接池的配置

  1. yml具体配置如下
    这里写图片描述
  2. Redis自定义配置

关于Redis的配置方式有很多,我知道有1.自动配置;2.手动配置;3.传统的xml文件也是可以的。在这里我只讲第2中,第二种比较灵活,符合spring boot风格。

  • 新建config包
  • 新建RedisConfiguration类
  package com.cherry.framework.config;
  
  import com.fasterxml.jackson.annotation.JsonAutoDetect;
  import com.fasterxml.jackson.annotation.PropertyAccessor;
  import com.fasterxml.jackson.databind.ObjectMapper;
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.beans.factory.annotation.Value;
  import org.springframework.boot.context.properties.ConfigurationProperties;
  import org.springframework.cache.Cache;
  import org.springframework.cache.CacheManager;
  import org.springframework.cache.annotation.CachingConfigurerSupport;
  import org.springframework.cache.annotation.EnableCaching;
  import org.springframework.cache.interceptor.CacheErrorHandler;
  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.jedis.JedisConnectionFactory;
  import org.springframework.data.redis.core.RedisTemplate;
  import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  import org.springframework.data.redis.serializer.RedisSerializer;
  import org.springframework.data.redis.serializer.StringRedisSerializer;
  import redis.clients.jedis.JedisPool;
  import redis.clients.jedis.JedisPoolConfig;
  
  /**
   * Redis 配置类
   *
   * @author Leon
   * @version 2018/6/17 17:46
   */
  @Configuration
  // 必须加,使配置生效
  @EnableCaching
  public class RedisConfiguration extends CachingConfigurerSupport {
  
      /**
       * Logger
       */
      private static final Logger lg = LoggerFactory.getLogger(RedisConfiguration.class);
  
      
      @Autowired
      private JedisConnectionFactory jedisConnectionFactory;
  
      @Bean
      @Override
      public KeyGenerator keyGenerator() {
          //  设置自动key的生成规则,配置spring boot的注解,进行方法级别的缓存
          // 使用:进行分割,可以很多显示出层级关系
          // 这里其实就是new了一个KeyGenerator对象,只是这是lambda表达式的写法,我感觉很好用,大家感兴趣可以去了解下
          return (target, method, params) -> {
              StringBuilder sb = new StringBuilder();
              sb.append(target.getClass().getName());
              sb.append(":");
              sb.append(method.getName());
              for (Object obj : params) {
                  sb.append(":" + String.valueOf(obj));
              }
              String rsToUse = String.valueOf(sb);
              lg.info("自动生成Redis Key -> [{}]", rsToUse);
              return rsToUse;
          };
      }
  
      @Bean
      @Override
      public CacheManager cacheManager() {
          // 初始化缓存管理器,在这里我们可以缓存的整体过期时间什么的,我这里默认没有配置
          lg.info("初始化 -> [{}]", "CacheManager RedisCacheManager Start");
          RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
                  .RedisCacheManagerBuilder
                  .fromConnectionFactory(jedisConnectionFactory);
          return builder.build();
      }
  
      @Bean
      public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory ) {
          //设置序列化
          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);
          // 配置redisTemplate
          RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
          redisTemplate.setConnectionFactory(jedisConnectionFactory);
          RedisSerializer stringSerializer = new StringRedisSerializer();
          redisTemplate.setKeySerializer(stringSerializer); // key序列化
          redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // value序列化
          redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化
          redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); // Hash value序列化
          redisTemplate.afterPropertiesSet();
          return redisTemplate;
      }
  
      @Override
      @Bean
      public CacheErrorHandler errorHandler() {
          // 异常处理,当Redis发生异常时,打印日志,但是程序正常走
          lg.info("初始化 -> [{}]", "Redis CacheErrorHandler");
          CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
              @Override
              public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
                  lg.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
              }
  
              @Override
              public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
                  lg.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
              }
  
              @Override
              public void handleCacheEvictError(RuntimeException e, Cache cache, Object key)    {
                  lg.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
              }
  
              @Override
              public void handleCacheClearError(RuntimeException e, Cache cache) {
                  lg.error("Redis occur handleCacheClearError:", e);
              }
          };
          return cacheErrorHandler;
      }
  
      /**
       * 此内部类就是把yml的配置数据,进行读取,创建JedisConnectionFactory和JedisPool,以供外部类初始化缓存管理器使用
       * 不了解的同学可以去看@ConfigurationProperties和@Value的作用
       *
       */
      @ConfigurationProperties
      class DataJedisProperties{
          @Value("${spring.redis.host}")
          private  String host;
          @Value("${spring.redis.password}")
          private  String password;
          @Value("${spring.redis.port}")
          private  int port;
          @Value("${spring.redis.timeout}")
          private  int timeout;
          @Value("${spring.redis.jedis.pool.max-idle}")
          private int maxIdle;
          @Value("${spring.redis.jedis.pool.max-wait}")
          private long maxWaitMillis;
  
          @Bean
          JedisConnectionFactory jedisConnectionFactory() {
              lg.info("Create JedisConnectionFactory successful");
              JedisConnectionFactory factory = new JedisConnectionFactory();
              factory.setHostName(host);
              factory.setPort(port);
              factory.setTimeout(timeout);
              factory.setPassword(password);
              return factory;
          }
          @Bean
          public JedisPool redisPoolFactory() {
              lg.info("JedisPool init successful,host -> [{}];port -> [{}]", host, port);
              JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
              jedisPoolConfig.setMaxIdle(maxIdle);
              jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
  
              JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
              return jedisPool;
          }
      }
  
  }

4.整合测试

在UserService的实现类中(业务层)进行缓存测试,注入RedisTemplate或StringRedisTemplate都可以。

package com.cherry.framework.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cherry.framework.dao.UserEntityMapper;
import com.cherry.framework.model.UserEntity;
import com.cherry.framework.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * User ServiceImpl
 *
 * @author Leon
 * @version 2018/6/14 17:12
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserEntityMapper userEntityMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 新增
     *
     * @param userEntity
     * @return
     */
    @Override
    @Transactional
    public int save(UserEntity userEntity) {
        userEntityMapper.insert(userEntity);
        return userEntity.getUserId();
    }

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    public PageInfo<UserEntity> findAllUserList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserEntity> list = userEntityMapper.selectAll();
        PageInfo<UserEntity> pageInfo = new PageInfo<>(list);
        // 具体使用
        redisTemplate.opsForList().leftPush("user:list", JSON.toJSONString(list));
        stringRedisTemplate.opsForValue().set("user:name", "张三");
        return pageInfo;
    }
}
  1. 使用postman访问对象controller的url
      /**
       * 列表查询
       *
       * @return
       */
      @RequestMapping(value = "/user/list")
      public PageInfo<UserEntity> findUserList(int pageNum, int pageSize) {
          PageInfo<UserEntity> pageInfo = userService.findAllUserList(pageNum, pageSize);
          return pageInfo;
      }
  1. 端口配置如下
  server:
    port: 8080
    servlet:
      path: /
  1. 访问url
    这里写图片描述
  2. 通过Redis Desktop Manager 进行查看
    这里写图片描述

三、总结

2.0整合在很多方面和1.5版本不一样,如果有问题参考官方英文文档,可以大大提高我们效率,(毕竟东西刚出,又没人翻译,只能看原版文档)

如果有说的不清楚的地方,在下面留言,我每天都会看博客,一起交流学习。最后晒出最后的总体结构图
这里写图片描述

Github地址:Spring Boot 2.X 整合Redis

  • 42
    点赞
  • 165
    收藏
    觉得还不错? 一键收藏
  • 75
    评论
Spring Boot中使用Spring Data Redis进行Redis Geo操作,需要在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.6.0</version> </dependency> ``` 然后在application.properties文件中配置Redis相关信息: ```properties # Redis spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 接下来,我们需要创建一个RedisGeoService来进行Geo操作: ```java @Service public class RedisGeoService { private final RedisTemplate<String, String> redisTemplate; public RedisGeoService(RedisTemplate<String, String> redisTemplate) { this.redisTemplate = redisTemplate; } /** * 添加地理位置信息 * * @param key 键 * @param longitude 经度 * @param latitude 纬度 * @param member 成员 * @return Long */ public Long add(String key, double longitude, double latitude, String member) { Point point = new Point(longitude, latitude); return redisTemplate.opsForGeo().add(key, point, member); } /** * 获取两个地理位置的距离 * * @param key 键 * @param member1 成员1 * @param member2 成员2 * @param unit 距离单位 * @return Distance */ public Distance distance(String key, String member1, String member2, Metric unit) { return redisTemplate.opsForGeo().distance(key, member1, member2, unit); } /** * 获取指定成员的地理位置 * * @param key 键 * @param members 成员 * @return List<Point> */ public List<Point> position(String key, String... members) { return redisTemplate.opsForGeo().position(key, members); } /** * 获取指定地理位置附近的成员 * * @param key 键 * @param longitude 经度 * @param latitude 纬度 * @param radius 半径 * @param unit 距离单位 * @return GeoResults<GeoLocation<String>> */ public GeoResults<GeoLocation<String>> nearBy(String key, double longitude, double latitude, double radius, Metric unit) { Circle circle = new Circle(longitude, latitude, new Distance(radius, unit)); GeoRadiusCommandArgs args = GeoRadiusCommandArgs.newGeoRadiusArgs().sortAscending(); return redisTemplate.opsForGeo().radius(key, circle, args); } } ``` 上述代码中,我们使用了RedisTemplate来进行Redis操作。RedisTemplate是Spring Data Redis提供的核心组件,用于执行Redis命令。 在RedisGeoService中,我们定义了四个方法来进行Geo操作: - add方法:添加地理位置信息。 - distance方法:获取两个地理位置的距离。 - position方法:获取指定成员的地理位置。 - nearBy方法:获取指定地理位置附近的成员。 使用Spring BootSpring Data Redis进行Geo操作非常方便,只需要定义一个RedisGeoService,并注入RedisTemplate即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 75
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值