zoukankan      html  css  js  c++  java
  • Redis中在项目中的使用

    打开Redis

    再到Redis目录cmd

    redis-server.exe redis.windows.conf

    然后在开一个窗口

    redis-cli.exe -h 127.0.0.1 -p 6379

    config get requirepass

    config set requirepass 123456

    auth 123456

    keys *查看

    然后在Java中连接Redis

    SpringColud中使用Redis我们需要写一个微服务

    pom

    <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.9.0</version>
            </dependency>
    View Code

    RedisUtils

    package cn.jiedada.hrm.util;
    
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;
    
    import java.io.IOException;
    import java.util.List;
    import java.util.Map;
    import java.util.Properties;
    import java.util.Set;
    
    /**
     * 获取连接池对象
     */
    public enum RedisUtils {
    
        INSTANCE;
    
        //连接池
        static JedisPool jedisPool = null;
    
        static {
            //1 创建连接池配置对象
            JedisPoolConfig config = new JedisPoolConfig();
            //2 进行配置-四个配置
            config.setMaxIdle(1);//最小连接数
            config.setMaxTotal(11);//最大连接数
            config.setMaxWaitMillis(10 * 1000L);//最长等待时间
            config.setTestOnBorrow(true);//测试连接时是否畅通
            //3 通过配置对象创建连接池对象
            Properties properties = null;
            try {
                properties = new Properties();
                properties.load(RedisUtils.class.getClassLoader().getResourceAsStream("redis.properties"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            String host = properties.getProperty("redis.host");
            String port = properties.getProperty("redis.port");
            String password = properties.getProperty("redis.password");
            String timeout = properties.getProperty("redis.timeout");
    
            jedisPool = new JedisPool(config, host, Integer.valueOf(port),Integer.valueOf(timeout), password);
        }
    
        //获取连接
        public Jedis getSource() {
            return jedisPool.getResource();
        }
    
        //关闭资源
        public void closeSource(Jedis jedis) {
            if (jedis != null) {
                jedis.close();
            }
    
        }
    
        /**
         * hash操作字符串==============================================
         */
        public List<String> hvals(String key) {
            Jedis jedis = getSource();
            List<String> hvals = jedis.hvals(key);
            closeSource(jedis);
            return hvals;
        }
        public Set<String> hkeys(String key) {
            Jedis jedis = getSource();
            Set<String> hkeys = jedis.hkeys(key);
            closeSource(jedis);
            return hkeys;
        }
    
        public Long hset(String key,String field,String value) {
            Jedis jedis = getSource();
            Long result = jedis.hset(key,field,value);
            closeSource(jedis);
            return result;
        }
        public String hmset(String key, Map<String,String> data) {
            Jedis jedis = getSource();
            String result = jedis.hmset(key,data);
            closeSource(jedis);
            return result;
        }
        public String hget(String key,String field) {
            Jedis jedis = getSource();
            String value = jedis.hget(key, field);
            closeSource(jedis);
            return value;
        }
        /**
         * hash操作byte[]==============================================
         */
        public List<byte[]> hvals(byte[] key) {
            Jedis jedis = getSource();
            List<byte[]> hvals = jedis.hvals(key);
            closeSource(jedis);
            return hvals;
        }
        public Set<byte[]> hkeys(byte[] key) {
            Jedis jedis = getSource();
            Set<byte[]> hkeys = jedis.hkeys(key);
            closeSource(jedis);
            return hkeys;
        }
    
        public Long hset(byte[] key,byte[] field,byte[] value) {
            Jedis jedis = getSource();
            Long result = jedis.hset(key,field,value);
            closeSource(jedis);
            return result;
        }
        public String hmset(byte[] key, Map<byte[],byte[]> data) {
            Jedis jedis = getSource();
            String result = jedis.hmset(key,data);
            closeSource(jedis);
            return result;
        }
        public byte[] hget(byte[] key,byte[] field) {
            Jedis jedis = getSource();
            byte[] value = jedis.hget(key, field);
            closeSource(jedis);
            return value;
        }
    
    
        /**
         * 删除key
         */
        public boolean del(String key) {
            Jedis jedis = getSource();
            long result  = jedis.del(key);
            closeSource(jedis);
            return result > 0;
        }
    
        /**
         * 设置字符值
         *
         * @param key
         * @param value :value是字符串,如果要存储对象,转成JSON字符串在存储
         */
        public void set(String key, String value) {
            Jedis jedis = getSource();
            jedis.set(key, value);
            closeSource(jedis);
        }
    
        /**
         * 设置
         * @param key
         * @param value
         */
        public void set(byte[] key, byte[] value) {
            Jedis jedis = getSource();
            jedis.set(key, value);
            closeSource(jedis);
        }
    
        /**
         *
         * @param key
         * @return
         */
        public byte[]  get(byte[] key) {
            Jedis jedis = getSource();
            try {
                return jedis.get(key);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                closeSource(jedis);
            }
            return null;
    
        }
    
        /**
         * 设置字符值
         *
         * @param key
         * @return :返回的是JSON格式的字符串 ,考虑转对象
         */
        public String get(String key) {
            Jedis jedis = getSource();
            try {
                return jedis.get(key);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                closeSource(jedis);
            }
    
            return null;
        }
    }
    View Code

    配置类

    redis.properties

    redis.host=127.0.0.1
    redis.port=6379
    redis.password=123456
    redis.timeout=30000
    View Code

    在yml中添加

    feign:
      hystrix:
        enabled: true #开启熔断支持

     写一个API接口 @GetMapping("/redis/get/{key}")最好把所以的参数都写完,不然Fegin调用的复制过去的时候会忘记加@RequestMapping("/sad")这个路径

    @RestController
    @RequestMapping("/sad")
    
    
     //redis/set/key=?&value=?
        @PostMapping("/redis/set")
        public AjaxResult set(@RequestParam("key") String key,@RequestParam("value") String value){
            try {
                RedisUtils.INSTANCE.set(key, value);
                return AjaxResult.me();
            }catch (Exception e){
                return AjaxResult.me().setSuccess(false).setResultObj(e.getMessage());
            }
        }
        //
        @GetMapping("/redis/get/{key}")
        public AjaxResult get(@PathVariable("key") String key){
            try {
                String s = RedisUtils.INSTANCE.get(key);
                return AjaxResult.me().setResultObj(s);
            }catch (Exception e){
                return AjaxResult.me().setSuccess(false).setResultObj(e.getMessage());
            }
        }
        @DeleteMapping("/redis/del/{key}")
        public AjaxResult del(@PathVariable("key") String key){
            try {
                boolean del = RedisUtils.INSTANCE.del(key);
                return AjaxResult.me();
            }catch (Exception e){
                return AjaxResult.me().setSuccess(false).setResultObj(e.getMessage());
            }
        }
    View Code

    写一个Fegin接口

    pom

    <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>

    配置类,这样我们不需要在该类中添加开启Fegin,最好强制扫描fegin接口

    //创建配置类
    @Configuration
    @EnableFeignClients("cn.jiedada.hrm.fegin")
    public class ClientConfig {
    }

    Fegin接口

    package cn.jiedada.hrm.fegin.client;
    
    import cn.jiedada.hrm.fegin.fallback.RedisFeginFallbackFactory;
    import cn.jiedada.hrm.util.AjaxResult;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.*;
    
    @FeignClient(value = "cache-service",fallbackFactory = RedisFeginFallbackFactory.class)
    public interface RedisFegin {
        @PostMapping("/redis/set")
        AjaxResult set(@RequestParam("key") String key, @RequestParam("value") String value);
        @GetMapping("/redis/get/{key}")
        public AjaxResult get(@PathVariable("key") String key);
        @DeleteMapping("/redis/del/{key}")
        public AjaxResult del(@PathVariable("key") String key);
    }
    View Code

    Fallback方法

    package cn.jiedada.hrm.fegin.fallback;
    
    import cn.jiedada.hrm.fegin.client.RedisFegin;
    import cn.jiedada.hrm.util.AjaxResult;
    import feign.hystrix.FallbackFactory;
    import org.springframework.stereotype.Component;
    
    @Component
    public class RedisFeginFallbackFactory implements FallbackFactory<RedisFegin>{
        @Override
        public RedisFegin create(Throwable throwable) {
            return new RedisFegin() {
                @Override
                public AjaxResult set(String key, String value) {
                    throwable.getMessage();
                    return AjaxResult.me().setSuccess(false).setResultObj("缓存错误需要重新缓存");
                }
    
                @Override
                public AjaxResult get(String key) {
                    throwable.getMessage();
                    return AjaxResult.me().setSuccess(false).setResultObj("不能够在缓存中获取");
                }
    
                @Override
                public AjaxResult del(String key) {
                    throwable.getMessage();
                    return AjaxResult.me().setSuccess(false).setResultObj("不能够清除缓存");
                }
            };
        }
    }
    View Code

    在课程中引入Fegin的包(这里我们要使用RedisController接口都需要通过HTTP协议所以需要写Fegin接口)

    然后注入Fegin接口

    然后我们获取课程则需要先从Redis中获取,然后判断是否有数据,如果没有数据则去数据库中查找,并且存入数据库中

    //在redis中获得CourseType
        private List<CourseType> getCoursesTypeByRedisOrDB() {
            //先从redis中获取如果没有再去DB中查找
            AjaxResult ajaxResult = redisFegin.get(CourseTypeConstants.Course_Type);
            if(ajaxResult.isSuccess() && ajaxResult.getResultObj()!=null){
                //因为我们redis中保存的为String所以需要转化为List<CourseType>
                String courseTypeString = ajaxResult.getResultObj().toString();
                return JSON.parseArray(courseTypeString,CourseType.class);
            }else {
                //如果没有则去DB中查询并且保存到redis中
                List<CourseType> courseTypes = baseMapper.selectList(null);
                String toCourseTypesString = JSON.toJSONString(courseTypes);
                System.out.println(toCourseTypesString);
                AjaxResult setAjaxResult1 = redisFegin.set(CourseTypeConstants.Course_Type, toCourseTypesString);
                if(!setAjaxResult1.isSuccess()){
                    log.error("课程不能够保存到redis中,保存失败");
                }
                return courseTypes;
            }
        }
    View Code
  • 相关阅读:
    SAP UI5 应用 XML 视图的加载逻辑分析
    作为一名 ABAP 资深顾问,下一步可以选择哪一门 SAP 技术作为主攻方向?
    一步步把 SAP UI5 应用部署到 SAP BTP Kyma 运行环境中去
    C++图像的拷贝
    C++图像裁减
    C++opencv图像的缩放
    C++typeid操作符--返回类型、变量、对象的类型名称
    C++opencv-像素操作
    C++虚析构函数
    C++openCV图像的读取、显示、保存、信息
  • 原文地址:https://www.cnblogs.com/xiaoruirui/p/13660618.html
Copyright © 2011-2022 走看看