spring boot 自学笔记(三) Redis集成—RedisTemplate

Spring boot 基于Spring,  Redis集成与Spring大同小异。

文章示例代码均以前篇笔记为基础增加修改,直接上代码:

pom.xml  Redis相关依赖:

<?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.vic</groupId>
	<artifactId>vic</artifactId>
	<version>0.1.0</version>

	<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>


application.properties增加redis相关属性:

#datasource
spring.datasource.jdbcUrl=jdbc:mysql://115.28.92.178:3306/wms?useUnicode\=true&characterEncoding\=utf8;autoReconnect\=true;maxReconnects\=10;connectTimeout\=180000;socketTimeout\=180000
spring.datasource.user=root
spring.datasource.password=xx
spring.datasource.driverClass=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
spring.redis.hostName=115.28.92.178
spring.redis.port=6379  
spring.redis.password=xxx
spring.redis.pool.maxActive=8  
spring.redis.pool.maxWait=-1  
spring.redis.pool.maxIdle=8  
spring.redis.pool.minIdle=0  
spring.redis.timeout=0






com.vic.config包中新增RedisConfig.java:

/**
 * 
 * @author vic
 * @desc redis config bean
 *
 */
@Configuration
@EnableAutoConfiguration
public class RedisConfig {

	private static Logger logger = Logger.getLogger(RedisConfig.class);
	
	@Bean
	@ConfigurationProperties(prefix="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;
	}
}


OK,此时Reddis已经集成完成,下面来对常用操作做一些封装测试:

新增IRedisService接口定义一些常用操作接口,以及添加实现类RedisServiceImpl,代码如下:


IRedisService.java

/**
 * 
 * @author vic
 * @desc redis service
 */
public interface IRedisService {
	
	public boolean set(String key, String value);
	
	public String get(String key);
	
	public boolean expire(String key,long expire);
	
	public <T> boolean setList(String key ,List<T> list);
	
	public <T> List<T> getList(String key,Class<T> clz);
	
	public long lpush(String key,Object obj);
	
	public long rpush(String key,Object obj);
	
	public String lpop(String key);
	
}

RedisServiceImpl.java

/**
 * 
 * @author vic
 * @desc resdis service
 *
 */
@Service
public class RedisServiceImpl implements IRedisService{

	@Autowired
	private RedisTemplate<String, ?> redisTemplate;
	
	@Override
	public boolean set(final String key, final String value) {
		boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
            	RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                return true;
            }
	    });
		return result;
	}

	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 <T> boolean setList(String key, List<T> list) {
		String value = JSONUtil.toJson(list);
		return set(key,value);
	}

	@Override
	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;
	}

	@Override
	public long lpush(final String key, Object obj) {
		final String value = JSONUtil.toJson(obj);
		long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            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;
	}

	@Override
	public long rpush(final String key, Object obj) {
		final String value = JSONUtil.toJson(obj);
		long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            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;
	}

	@Override
	public String lpop(final String key) {
		String result = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            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;
	}

}


其中的JSONUtil类,可下载demo代码查看,其实就是一个JSON的工具类。


在ExampleController中添加测试方法:

@RestController
public class ExampleController {

	@Autowired
	private IUserService userService;
	
	@Autowired
	private IRedisService redisService;
	
	@RequestMapping("/users")
	public ResponseModal users(){
		List<User> users = userService.getAll();
		ResponseModal modal = new ResponseModal(200,true,"",users);
		return modal;
	}
	
	@RequestMapping("/redis/set")
	public ResponseModal redisSet(@RequestParam("value")String value){
		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);
	}
	
}


运行Application的main函数

浏览器输入:http://localhost:8080/redis/set?value=vic  响应结果:

{"code":200,"success":true,"message":"success","response":null}

浏览器输入:http://localhost:8080/redis/get  响应结果:

{"code":200,"success":true,"message":"success","response":"vic"}


示例代码下载



武汉指玄网络科技



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/i_vic/article/details/53081241
个人分类: spring boot
上一篇spring boot 自学笔记(二) 集成Mybatis
下一篇spring boot 自学笔记(四) Redis集成—Jedis
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭