1. 程式人生 > 實用技巧 >Socket套接字程式設計

Socket套接字程式設計

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之間的專案轉換更為方便

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());
        }
    }
}