上一篇讲解了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