1. 程式人生 > >十分鐘搞定SpringBoot 和Redis 實戰整合

十分鐘搞定SpringBoot 和Redis 實戰整合

這裡,對於springboot和redis 不做介紹,大家可以自己去查詢資料~~~~~~~~~~~

windows下本地安裝 redis 安裝

話不多說,來就是開搞!

專案框架

具體實現程式碼

pom檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.vk.ioc</groupId>
	<artifactId>vk-ioc-redis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>vanke-ioc-redis</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-redis</artifactId>
			<version>1.3.8.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.38</version>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.41</version>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.0</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>2.0.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>2.0.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-test</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.3.17.RELEASE</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

application.yml

spring:
  datasource:
        # 驅動配置資訊
        url: jdbc:mysql://localhost:3306/sb?useUnicode=true&characterEncoding=utf8
        username: root
        password: root
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver

        # 連線池的配置資訊
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
  redis:
    jedis:
      pool:
        max-active: 100
        max-wait: 10000
        max-idle: 10
    host: 127.0.0.1
    port: 6379
    password: 123456
    timeout: 0

RedisConf

獲取application.yml配置檔案一些引數

@Configuration
@EnableAutoConfiguration
public class RedisConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.redis.jedis.pool")
    public JedisPoolConfig getRedisConf() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        return jedisPoolConfig;
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.redis")
    public JedisConnectionFactory getConnectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setUsePool(true);
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
        return jedisConnectionFactory;
    }
    @Bean
    public RedisTemplate<?, ?> getRedisTemplate() {
        JedisConnectionFactory factory = getConnectionFactory();
        RedisTemplate<?, ?> template = new StringRedisTemplate(factory);
        return template;
    }
}

以上三個方法分別為獲取JedisPoolConfig配置、獲取JedisConnectionFactory工廠和獲取RedisTemplate模板。

@Configuration 註解是用於定義配置類,可替換xml配置檔案,被註解的類內部包含有一個或多個被@Bean註解的方法,這些方法將會被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext類進行掃描,並用於構建bean定義,初始化Spring容器。

@EnableAutoConfiguration 註解是啟用Spring應用程式上下文的自動配置,嘗試猜測和配置您可能需要的bean。自動配置類通常基於類路徑和定義的bean應用。

@ConfigurationProperties 註解是用於讀取配置檔案的資訊,在這裡是讀取配置在yml裡的redis的相關配置項。

@Bean 註解用在方法上,告訴Spring容器,你可以從下面這個方法中拿到一個Bean

在包裡建立RedisService介面,在這個介面定義了一些redis的基本操作。在這裡我把所有存取操作都封裝成了基於json字串完成,就沒有對於list或者對於object等單獨定義方法。所有的資料型別的儲存都由程式碼轉換成json字串方式進行。所以這裡就只有四個方法。

RedisService

public interface RedisService {
    /**
     * set存資料
     *
     * @param key
     * @param value
     * @return
     */
    boolean set(String key, String value);

    /**
     * get獲取資料
     *
     * @param key
     * @return
     */
    String get(String key);

    /**
     * 設定有效天數
     *
     * @param key
     * @param expire
     * @return
     */
    boolean expire(String key, long expire);

    /**
     * 移除資料
     *
     * @param key
     * @return
     */
    boolean remove(String key);
}

RedisServiceImpl

@Service
public class RedisServiceImpl implements RedisService {
    @Autowired
    private RedisTemplate<String, ?> redisTemplate;

    @Override
    public boolean set(final String key, final String value) {
//     execute,   實現對於redis資料的操作
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                //StringRedisSerializer來做序列化,不過這個方式的泛型指定的是String
                // 只能傳String進來。所以專案中採用json字串做redis的互動。
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                return true;
            }
        });
        return result;
    }

    @Override
    public String get(final String key) {
        String result = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] value = connection.get(serializer.serialize(key));
                return serializer.deserialize(value);
            }
        });
        return result;
    }

    @Override
    public boolean expire(final String key, long expire) {
        return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    @Override
    public boolean remove(final String key) {
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                connection.del(key.getBytes());
                return true;
            }
        });
        return result;
    }
}

execute()方法,這樣能實現對於redis資料的操作。
redis儲存的資料會在記憶體和硬碟上儲存,所以需要做序列化;這個裡面使用的StringRedisSerializer來做序列化,不過這個方式的泛型指定的是String,只能傳String進來。所以採用json字串做redis的互動。

Person

class Person {
    private String name;
    private String sex;

    public Person() {

    }

    public Person(String name, String sex) {
        this.name = name;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

測試  VkeIocRedisApplicationTests

/**
 * 測試
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class VkeIocRedisApplicationTests {
    //使用json字串進行互動,引入fastjson的JSONObject類
    private JSONObject json = new JSONObject();
    //	@Autowired註解把redisService注入進來
    @Autowired
    private RedisService redisService;

    @Test
    public void contextLoads() throws Exception {
    }


    /**
     * 插入字串
     */
    @Test
    public void setString() {
        redisService.set("redis_string_test", "springboot redis test");
    }

    /**
     * 獲取字串
     */
    @Test
    public void getString() {
        String result = redisService.get("redis_string_test");
        System.out.println(result);
    }

    /**
     * 插入物件
     */
    @Test
    public void setObject() {
        Person person = new Person("person", "male");
        redisService.set("redis_obj_test", json.toJSONString(person));
    }

    /**
     * 獲取物件
     */
    @Test
    public void getObject() {
        String result = redisService.get("redis_obj_test");
        Person person = json.parseObject(result, Person.class);
        System.out.println(json.toJSONString(person));
    }

    /**
     * 插入物件List
     */
    @Test
    public void setList() {
        Person person1 = new Person("person1", "male");
        Person person2 = new Person("person2", "female");
        Person person3 = new Person("person3", "male");

        List<Person> list = new ArrayList<>();
        list.add(person1);
        list.add(person2);
        list.add(person3);
        redisService.set("redis_list_test", json.toJSONString(list));
    }

    /**
     * 獲取list
     */
    @Test
    public void getList() {
        String result = redisService.get("redis_list_test");
        List<String> list = json.parseArray(result, String.class);
        System.out.println(list);
    }

    @Test
    public void remove() {
        redisService.remove("redis_test");
    }

}

使用json字串進行互動,所以引入fastjson的JSONObject類

然後執行測試類,結果如下:

在redis視覺化管理工具檢視時間

································注意:執行測試的時候,先要啟動redis服務-----------------------------------------------------------------

定位到 redis的目錄下,如下,就是啟動服務。

回車鍵

但是不要關閉視窗,關閉視窗就相當於關閉服務。

可能遇到問題

Caused by: redis.clients.jedis.exceptions.JedisDataException: ERR Client sent AUTH, but no password is set

ok啦~~~~~~~~·溜溜了

相關推薦

分鐘SpringBoot Redis 實戰整合

這裡,對於springboot和redis 不做介紹,大家可以自己去查詢資料~~~~~~~~~~~ windows下本地安裝 redis 安裝 話不多說,來就是開搞! 專案框架 具體實現程式碼 pom檔案 <?xml version="1.0" en

分鐘mongodb副本集

Java mongodb mongodb副本集配置 最近項目中用到了mongodb,由於是用mongodb來記錄一些程序的日誌信息和日常的統計,為了增加應用的可靠性,一直在找mongodb集群的一些資料,下面

分鐘macOS tensorflow + opencv配置

jpg bus main 個人 urn hub 打印 就是 學校 隔壁小白都簡單哭了 準備: MacOS(我的系統是10.12.6,比較懶很少更新) python 3.6(忘掉2.7吧~已經是遺留版本啦~下載地址 https://www.python.org/downloa

運維日常:五分鐘PHP的redis問題

stand GNU C execution top depend sbin ash arguments lib 一、前言 1.需求 2.解決LNMP環境中的PHP缺少redis擴展包,導致訪問頁面報錯500,處理問題,安裝PHP擴展功能redis。 下面記錄整個過程,如果不

分鐘windowsLinux系統的共享訪問

需求 區域網內部的A/B兩臺機器需要相互之間傳輸檔案 假設 A為Ubuntu 16.04LTS系統, B為Win10系統, A,B位於區域網內部,具有共同的網段。 實現方法 在A上興建一個共享資料夾,只要B可以通過內網來訪問該資料夾,即可實現AB的資料傳輸了 實現步驟 1

分鐘PCA主成分分析

PCA主成分分析概述 在資料建模當中我們經常會聽到一個詞叫做降維,首先咱們先來嘮一嘮資料為啥要降維呢?最主要的原因還是在於一方面使得所需要計算的量更少啦,想象一下一個100維的資料和一個10維資料計算的速度肯定是不一樣的,另一方面如果我們的資料中有很無關特徵,這些對結果看起來沒什麼促進的作用

MongoDB分鐘CRUD

一、環境準備 MongoDB環境安裝參照 MongoDBWindows平臺安裝 二、建立專案,新增MongoDB驅動依賴Jar <dependency> <grou

分鐘Vue搭建

既然你來到了這裡,肯定你知道vue是什麼,具體我也就不說了。 廢話不多說。 Vue推薦開發環境 Node.js 6.2.0、npm 3.8.9、webpack 1.13、vue

分鐘pandas

這是對官方doc的一個翻譯 原帖地址 :http://www.cnblogs.com/chaosimple/p/4153083.html 官方地址 :http://pandas.pydata.org/pandas-docs/stable/10min.html 一、 

分鐘pandas(Python資料預處理庫)

本文是對pandas官方網站上《10Minutes to pandas》的一個簡單的翻譯,原文在這裡。這篇文章是對pandas的一個簡單的介紹,詳細的介紹請參考:Cookbook 。習慣上,我們會按下面格式引入所需要的包: 一、           建立物件 1、可以

poi實現excel上傳下載 親自實踐 教你分鐘

今天要實現一個上傳excel的功能,之前寫過很多次,但是都沒有詳細整理過,今天整理下,方便以後直接拿來拷貝首先從前臺來看,看了很多案例,基本兩種方法:一種是form表單提交,一種是非同步ajax方式。在這裡我選擇ajax方式,因為我想要在前臺上傳完成後給使用者提示上傳成功還是

項目實戰:iOS極光推送集成(30分鐘

adg append ati 技術分享 tro markdown ocs sym xcode 推送有非常多,如個推、友盟、融雲和極光等等。在這裏就講下怎樣使用極光推送。主要內容是將官方文檔資料詳細匯總並一步一步集成到項目中,您也能夠直接去官方文檔閱

10分鐘Lync 2010Quintum AF集成

Lync Quintum AF集成 接線拓撲接線方法:l 電信直線直接接在Quintum AF的FXO口上l AF采用RJ45接入網絡 使用效果:l PSTN用戶撥打直線的號碼,會聽到二次撥號音,然後再輸入Lync用戶的分機號碼就可以直接振鈴Lync用戶l Lync用戶直接撥打外部號碼就可以直

Python資料處理之( 八)10分鐘matplotlib

Matplotlib 簡介 1.1 為什麼用 Matplotlib 1.2 Matplotlib 安裝 基本使用 2.1 基本用法 2.2 figure 影象 2.3 設定座標軸1 2.4 設定座標軸2 2.5 Legend 圖例 2.6 Annota

redis- 使用info輕鬆調優-《每日五分鐘大資料》

本文根據redis的info命令檢視redis的記憶體使用情況以及state狀態,來觀察redis的執行情況以及需要作出的相應優化。 info 1.memory used_memory:13409011624 #used_memory=實際快取佔用的記憶體+Redis自身執行所佔用的記憶體(如元資料、lu

爆炸啊,元件化MVP

文章目錄: - 前言 - 說明 - 如何使用 - 其他說明 - 更多 - TODO - 相關文章 - 關於個人 ## 前言 皮!就是這麼皮 什麼?想用比較新比較火的元件化和MVP這麼辦? 十秒帶你過山車式

用sshsocat分分鐘Linux各種埠轉發

本地埠對映 小明寫了一個Web服務,監聽hosta上8080埠,小王現在想訪問這個服務,有沒有快速的方法? SSH本地埠轉發 其實很簡單,小明只需要做這兩件事情: 申請一臺帶公網IP的公有云伺服器hostb,我們假設ip地址是12.34.56.78 在h

10分鐘輕鬆SpringBoot整合RabbitMQ教程

第一步:在專案pom.xml檔案中,新增pring-boot-starter-amqp 依賴<dependency> <groupId>org.springframework.boot</groupId> <artifac

10分鐘輕鬆SpringBoot整合Activiti6教程

第一步在專案pom.xml檔案中新增所需依賴<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http:/

Python:10分鐘不寫代碼的爬蟲

出現 ring swe 導入 gem 取數據 bbb del delay 代碼自己敲 使用 Chrome 瀏覽器插件 Web Scraper 可以輕松實現網頁數據的爬取,不寫代碼,鼠標操作,點哪爬哪,還不用考慮爬蟲中的登陸、驗證碼、異步加載等復雜問題。 Web Scrap