關於Spring boot 與 redis 的集成,以及Spring中redis的使用

上一篇講解了redis的搭建。本篇就如何在項目中使用redis作一個簡單的介紹java

框架:Spring boot + mavenmysql

咱們在Pom中添加redis與Spring的依賴包git

個人pom以下:github

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.zx</groupId>
  <artifactId>SpringCloudTwo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <properties>  
        <java.version>1.7</java.version>  
    </properties>  
      
    <parent>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-parent</artifactId>  
        <version>1.3.8.RELEASE</version>  
    </parent>  
  
    <dependencies>  
        <!-- spring boot -->  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-web</artifactId>  
        </dependency>  
          
        <!-- mybatis -->  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-jdbc</artifactId>  
        </dependency>  
  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis-spring</artifactId>  
            <version>1.2.2</version>  
        </dependency>  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis</artifactId>  
            <version>3.2.8</version>  
        </dependency>  
  
        <dependency>  
            <groupId>mysql</groupId>  
            <artifactId>mysql-connector-java</artifactId>  
        </dependency>  
  
        <dependency>  
            <groupId>com.mchange</groupId>  
            <artifactId>c3p0</artifactId>  
            <version>0.9.2.1</version>  
        </dependency>  
          
          
        <!-- redis -->  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-redis</artifactId>  
  
        </dependency>  
          
        <!--Gson-->    
        <dependency>    
            <groupId>com.google.code.gson</groupId>    
            <artifactId>gson</artifactId>    
        </dependency>    
	          
    </dependencies>  
    <build>  
        <plugins>  
            <plugin>  
                <groupId>org.springframework.boot</groupId>  
                <artifactId>spring-boot-maven-plugin</artifactId>  
            </plugin>  
        </plugins>  
    </build>  
</project>

 

載入jar包以後web

咱們建立一個redis的配置類 以下:redis

package Controller;

import org.apache.log4j.Logger;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import redis.clients.jedis.JedisPoolConfig;

@Configuration//把一個類做爲一個IoC容器,它的某個方法頭上若是註冊了@Bean,就會做爲這個Spring容器中的Bean。  
@EnableAutoConfiguration//這個註解告訴Spring Boot根據添加的jar依賴猜想你想如何配置Spring  
public class RedisConfig {  
  
    private static Logger logger = Logger.getLogger(RedisConfig.class);  
      
    @Bean//將返回值 交給Spring託管
    @ConfigurationProperties(prefix="spring.redis")//從配置文件中獲取spring.redis的配置  
    public JedisPoolConfig getRedisConfig(){  
        JedisPoolConfig config = new JedisPoolConfig();  
        return config;  
    }  
      
    @Bean  
    @ConfigurationProperties(prefix="spring.redis")  
    public JedisConnectionFactory getConnectionFactory(){  
        JedisConnectionFactory factory = new JedisConnectionFactory();  
        JedisPoolConfig config = getRedisConfig();  
        factory.setPoolConfig(config);  
        logger.info("JedisConnectionFactory bean init success.");  
        return factory;  
    }  
      
      
    @Bean  
    public RedisTemplate<?, ?> getRedisTemplate(){  
        RedisTemplate<?,?> template = new StringRedisTemplate(getConnectionFactory());  
        return template;  
    }  
}

這個類在spring容器初始化的時候就會執行,讀取默認配置文件application.properties 並託管上面的定義的對象。spring

其中配置文件默認存在於src/main/resources/目錄下sql

#datasource
#數據庫鏈接  
spring.datasource.url=jdbc\:mysql\://localhost\:3306/zx
#數據庫用戶名
spring.datasource.username=root
#數據庫密碼  
spring.datasource.password=
#數據庫驅動  
spring.datasource.driverClassName=com.mysql.jdbc.Driver
#數據庫最大鏈接數
spring.datasource.maxActive=100  
spring.datasource.initialPoolSize=5  
spring.datasource.minPoolSize=5  
spring.datasource.maxPoolSize=20  
spring.datasource.maxStatements=100  
spring.datasource.maxIdleTime=3600  
spring.datasource.acquireIncrement=2  
spring.datasource.acquireRetryAttempts=10  
spring.datasource.acquireRetryDelay=600  
spring.datasource.testConnectionOnCheckin=true  
spring.datasource.idleConnectionTestPeriod=1200  
spring.datasource.checkoutTimeout=100000  
  
#redis 
#redis主機地址 
spring.redis.hostName=192.168.6.96
#redis主機端口
spring.redis.port=6379
#redis連接密碼
spring.redis.password=
spring.redis.pool.maxActive=8
spring.redis.pool.maxWait=-1
spring.redis.pool.maxIdle=8
spring.redis.pool.minIdle=0
spring.redis.timeout=0

配置完成以後,咱們要完成的就是封裝redis的操做數據庫

思路是:咱們經過Spring的依賴注入 獲取RedisTemplate對象,經過RedisTemplate調用execute方法apache

去執行操做,並返回一個泛型操做,類結構圖以及類的定義解析以下:

附上的圖片過小,放大查看。我把主要的幾個單獨列出來以下

並附上execute源碼:

類結構解析以及代碼分析就此,下面貼上我定義的操做代碼

package Controller;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

@Service  
public class RedisServiceImpl implements IRedisService{  
  
    @Autowired//經過Spring依賴注入 redisTemlpate  
    private RedisTemplate<String, ?> redisTemplate;  
    //往Redis設置值
    public boolean set(final String key, final String value) {  
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {

			public Boolean doInRedis(RedisConnection connection)
					throws DataAccessException {
				RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
                connection.set(serializer.serialize(key), serializer.serialize(value));  
                return true;  
			}  
        });  
        return result;  
    }  
    //從Redis獲取值
    public String get(final String key){  
        String result = redisTemplate.execute(new RedisCallback<String>() {  
            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;  
    }  
  
    public boolean expire(final String key, long expire) {  
        return redisTemplate.expire(key, expire, TimeUnit.SECONDS);  
    }  
    //往Redis設置list類型值
    public <T> boolean setList(String key, List<T> list) {  
        String value = JSONUtil.toJson(list);  
        return set(key,value);  
    }  
    //從Redis獲取list類型值
    public <T> List<T> getList(String key,Class<T> clz) {  
        String json = get(key);  
        if(json!=null){  
            List<T> list = JSONUtil.toList(json, clz);  
            return list;  
        }  
        return null;  
    }  
  //往list頭添加元素
    public long lpush(final String key, Object obj) {  
        final String value = JSONUtil.toJson(obj);  
        long result = redisTemplate.execute(new RedisCallback<Long>() {  
            public Long doInRedis(RedisConnection connection) throws DataAccessException {  
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
                long count = connection.lPush(serializer.serialize(key), serializer.serialize(value));  
                return count;  
            }  
        });  
        return result;  
    }  
    //往list尾添加元素
    public long rpush(final String key, Object obj) {  
        final String value = JSONUtil.toJson(obj);  
        long result = redisTemplate.execute(new RedisCallback<Long>() {  
            public Long doInRedis(RedisConnection connection) throws DataAccessException {  
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
                long count = connection.rPush(serializer.serialize(key), serializer.serialize(value));  
                return count;  
            }  
        });  
        return result;  
    }  
  //往list頭刪除元素
    public String lpop(final String key) {  
        String result = redisTemplate.execute(new RedisCallback<String>() {  
            public String doInRedis(RedisConnection connection) throws DataAccessException {  
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
                byte[] res =  connection.lPop(serializer.serialize(key));  
                return serializer.deserialize(res);  
            }  
        });  
        return result;  
    }
  
}

控制器類

package Controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController  
public class ExampleController {  
  
      
    @Autowired  
    private IRedisService redisService;  
    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;
      
    @RequestMapping("/redis/set")  
    public ResponseModal redisSet(@RequestParam("value") String value){  
    	System.out.println(jedisConnectionFactory.getPassword());
        boolean isOk = redisService.set("name", value);  
        return new ResponseModal(isOk ? 200 : 500, isOk, isOk ? "success" : "error" , null);  
    }  
      
    @RequestMapping("/redis/get")  
    public ResponseModal redisGet(){  
        String name = redisService.get("name");  
        return new ResponseModal(200, true,"success",name);  
    }  
      
}

在配置這些的過程當中 碰到的問題有:

在訪問/redis/set?name=xxx的時候 出現500錯誤:err invalid password

這個錯是由於密碼配置錯誤,我在配置文件後面多加了幾個空格,致使連接失敗

添加數據庫配置的時候 根據Spring 的版本不一樣,數據庫參數名有所不一樣這個要注意。

若是在pom包中加入mybatis的時候可是並不作數據庫連接配置的話 就會報錯

 Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

因此 這個添加配置的時候要注意

github 項目地址:https://github.com/EZreal-zhangxing/Spring-boot-redis.git

相關文章
相關標籤/搜索