blogSite

我是谁?我在哪儿?我在干什么?

View project on GitHub

spring boot使用Redis

CentOS 7下安装Redis

  • 下载地址:https://download.redis.io/releases/
  • 下载:# wget https://download.redis.io/releases/redis-6.2.4.tar.gz
  • 解压:# tar -zxvf redis-6.2.4.tar.gz
  • 进入目录,# cd redis-6.2.4,后执行编译# make
  • 安装并指定安装目录# make install PREFIX=/usr/local/redis
  • 进入安装目录# cd /usr/local/redis/bin/后启动服务# ./redis-server,这种方式为前台启动
  • 后台启动redis
    1. 从redis源码目录中赋值reids.conf到reids的安装目录# cp /temp/redis-6.2.4/redis.conf /usr/local/redis/bin/
    2. 修改 redis.conf 文件,把 daemonize no 改为 daemonize yes
    3. 后台启动# ./redis-server redis.conf
    4. 查看是否启动成功# ps -ef | grep redis
  • 连接本地redis方法# ./redis-cli -h 127.0.0.1 -p 6379./redis-cli -h ip地址 -p 端口号
  • 停止# ./redis-cli shutdown,有时候停不了,不知道为什么

最终方案

  • NAS安装redis,然后通过nginx进行代理
stream {

  server {
          listen 6379;
          proxy_connect_timeout 1s;
          proxy_timeout 3s;
          proxy_pass redis;
  }

  upstream redis {
          server 101.40.21.39:6379 max_fails=3 fail_timeout=30s; # 101.40.21.39 为redis所在服务器的ip地址
  }

}
  • 远程链接到redis(可以使用vs code然后安装redis插件),然后在redis的命令行执行> config set requirepass 123456,设置redis的链接密码;使用> config get requirepass查看密码;

spring boot集成redis

  1. 修改pom.xml文件
     <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-redis</artifactId>
     </dependency>
    
  2. 修改application.properties配置文件
     #Redis配置
     #Redis服务器地址
     spring.redis.host=127.0.0.1
     #Redis服务器连接端口
     spring.redis.port=6379
     #Redis服务器连接密码(默认为空)
     spring.redis.password=123456
     #连接池最大连接数(使用负值表示没有限制)
     spring.redis.pool.max-active=8
     # 连接池最大阻塞等待时间(使用负值表示没有限制),单位毫秒
     spring.redis.pool.max-wait=-1 
     # 连接池中的最大空闲连接
     spring.redis.pool.max-idle=8 
     # 连接池中的最小空闲连接
     spring.redis.pool.min-idle=0 
     # 连接超时时间(毫秒)
     spring.redis.timeout=10000
    
  3. Redis配置类
     package top.z_f.simpleerp.configures;
    
     import org.springframework.cache.annotation.CachingConfigurerSupport;
     import org.springframework.cache.annotation.EnableCaching;
     import org.springframework.context.annotation.Configuration;
     import org.springframework.data.redis.connection.RedisConnectionFactory;
     import org.springframework.data.redis.core.RedisTemplate;
     import org.springframework.data.redis.serializer.StringRedisSerializer;
    
     /**
      * Redis配置类
     * @author zhangzhen
     * @date 2021-06-23
     *
     */
     @Configuration
     @EnableCaching
     public class RedisConfiguration extends CachingConfigurerSupport {
    
       /**
        * redisTemplate相关配置
        * @param factory
        * @return
        */
       public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
         RedisTemplate<String, Object> template = new RedisTemplate<>();
         // 配置链接工厂
         template.setConnectionFactory(factory);
         // 使用StringRedisSerializer来序列化和反序列化redis的key值
         template.setKeySerializer(new StringRedisSerializer());
         // 使用StringRedisSerializer来序列化和反序列化redis的value值
         template.setValueSerializer(new StringRedisSerializer());
            
         return template;
       }
     }
    
  4. Redis工具类
     package top.z_f.simpleerp.utils;
    
     import java.util.Collection;
     import java.util.concurrent.TimeUnit;
    
     import org.springframework.beans.factory.annotation.Autowired;
     import org.springframework.data.redis.core.RedisTemplate;
     import org.springframework.stereotype.Service;
    
     import lombok.extern.slf4j.Slf4j;
    
     /**
      * @author zhangzhen
     * @date 2021-06-23
     *
     */
     @Slf4j
     @Service
     public class RedisUtil {
          
       @Autowired
       private RedisTemplate<String, Object> redisTemplate;
          
       /**
        * 根据key 获取过期时间
        * @param key 不能为null
        * @return 时间(秒) 返回0代表为永久有效
        */
       public long getExpire(String key) {
         return redisTemplate.getExpire(key, TimeUnit.SECONDS);
       }
          
       /**
        * 判断key 是否存在
        * @param key
        * @return true 存在  false 不存在
        */
       public boolean hasKey(String key) {
         try {
           return redisTemplate.hasKey(key);
         } catch (Exception e) {
           e.printStackTrace();
           log.error("判断在redis中是否有key异常,ex >> " + e.getMessage());
           return false;
         }
       }
          
       /**
        * 根据key 删除
        * @param key
        */
       public void delKey(String key) {
         try {
           redisTemplate.delete(key);			
         } catch (Exception e) {
           e.printStackTrace();
           log.error("delKey 异常 : " + e.getMessage());
         }
       }
          
       /**
        * 根据keys 批量删除
        * @param keys
        */
       public void delKeys(Collection<String> keys) {
         try {
           redisTemplate.delete(keys);			
         } catch (Exception e) {
           e.printStackTrace();
           log.error("delKeys 异常 : " + e.getMessage());
         }
       }
          
       /**
        * 普通存入缓存
        * @param key
        * @param value
        * @return true 成功  false 失败
        */
       public boolean set(String key, Object value) {
         try {
           redisTemplate.opsForValue().set(key, value);
           return true;
         } catch (Exception e) {
           e.printStackTrace();
           log.error("set 异常: " + e.getMessage());
           return false;
         }
       }
    
       /**
        * 普通存入并设置失效时间
        * @param key
        * @param value
        * @param time 时间(秒)
        * @return true 成功  false 失败
        */
       public boolean set(String key, Object value, long time) {
         try {
           boolean result = false;
           if (time > 0) {
             redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
             result = true;
           } else {
             result = set(key, value);
           }
           return result;
         } catch (Exception e) {
           e.printStackTrace();
           log.error("set 异常 :" + e.getMessage());
           return false;
         }
       }
          
       /**
        * 根据key获取value
        * @param key
        * @return
        */
       public Object get(String key) {
         try {
           return redisTemplate.opsForValue().get(key);
         } catch (Exception e) {
           e.printStackTrace();
           log.error("get 异常: " + e.getMessage());
           return null;
         }
       }
    
       // TODO 待继续添加
     }
    

spring的一些知识

  • @Component, @Service, @Controller, @Repository是spring注解,注解后可以被spring框架所扫描并注入到spring容器来进行管理
  • @Component是通用注解,其他三个注解是这个注解的拓展,并且具有了特定的功能
  • @Repository注解在持久层中,具有将数据库操作抛出的原生异常翻译转化为spring的持久层异常的功能。
  • @Controller层是spring-mvc的注解,具有将请求进行转发,重定向的功能。
  • @Service层是业务逻辑层注解,这个注解只是标注该类处于业务逻辑层。 用这些注解对应用进行分层之后,就能将请求处理,义务逻辑处理,数据库操作处理分离出来,为代码解耦,也方便了以后项目的维护和开发。

参考文档

上一篇:spring boot中Controller获取前台参数方式 下一篇:spring boot集成shiro

首页 > 学习总览 > 开发语言 > Java