zoukankan      html  css  js  c++  java
  • springboot整合redis

    springboot整合redis

    1. 依赖

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
    </dependency>
    

    2. 配置文件

    创建一个redis.properties

    # 配置单台redis
    redis.host=192.168.126.129
    redis.port=6379
    

    3. 编辑配置类

    @Configuration  //标识我是配置类
    @PropertySource("classpath:/properties/redis.properties") // 读取配置文件
    public class RedisConfig {
    
        @Value("${redis.host}")
        private String  host;
        @Value("${redis.port}")
        private Integer port;
    
        @Bean
        public Jedis jedis(){
            //数据写死?????????
            return new Jedis(host,port);
        }
    }
    

    4. 测试

    @SpringBootTest //需要依赖spring容器,从容器中动态的获取对象
    public class TestRedis {
    
        @Autowired
        private Jedis jedis;
    
        @Test
        public void test01(){
            //1.向redis中保存数据
            jedis.set("2004", "哈哈哈 今天下雨了 不负众望");
            //2.从redis中获取数据
            String value = jedis.get("2004");
            System.out.println(value);
        }
    }
    

    关于保存数据

    redis我们通常用它来保存我们的java数据, 例如, 对象, 集合等信息

    通常我们会使用字符串的方式进行保存, 即把java对象转换为JSON格式的字符串进行保存

    取出的时候解析JSON字符串, 重新生成对象

    JSON工具类

    用于对象和json之间的项目转换更为方便

    public class ObjectMapperUtil {
    
        private static final ObjectMapper MAPPER = new ObjectMapper();
    
        /**
         * 封装API 将对象转化为JSON
         */
        public static String toJSON(Object object) {
            if (object == null) {
                throw new RuntimeException("传入的对象不能为null");
            }
            try {
                return MAPPER.writeValueAsString(object);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            }
        }
    
        /**
         * 将JSON串转为对象, 用户传递什么类型, 则返回什么对象
         */
        public static <T> T toObject(String json, Class<T> target) {
            // 1. 校验参数是否有效
            if (json == null || "".equals(json) || target == null) {
                throw new RuntimeException("参数不能为null");
            }
    
            // 2. 执行业务处理
            try {
                T t = MAPPER.readValue(json, target);
                return t;
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            }
        }
    }
    
  • 相关阅读:
    前端工程师基础课程作业
    对于API接口设计的几点看法
    socket socket.io
    移动端布局
    angularJS
    bootstrop的应用
    jquery基础
    html5本地存储
    ajax
    数据库类型
  • 原文地址:https://www.cnblogs.com/zpKang/p/13497501.html
Copyright © 2011-2022 走看看