SpringBoot(十五):SpringBoot整合Redis
一、环境准备
-
Redis-x64-3.2.100.zip SpringBoot 1.5.10.RELEASE
Redis-x64-3.2.100.zip 下载地址:
pom依赖:
<!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
二、项目结构
三、代码详情
application.yml
spring: # Redis 配置信息 redis: database: 0 host: 127.0.0.1 port: 6379 # password: timeout: 3000 pool: max-active: 200 max-wait: 1000 max-idle: 500 min-idle: 50
RedisConfiguration.java
package cn.saytime.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * @author zh * @ClassName cn.saytime.config.RedisConfiguration * @Description */ @Configuration public class RedisConfiguration { @Autowired private JedisConnectionFactory jedisConnectionFactory; @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.setConnectionFactory(jedisConnectionFactory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new JdkSerializationRedisSerializer()); template.afterPropertiesSet(); return template; } }
User.java
package cn.saytime.domain; import java.io.Serializable; /** * @author zh * @ClassName cn.saytime.domain.User * @Description */ public class User implements Serializable { private int id; private String name; // getter setter constructor toString }
测试类 SpringbootRedisApplicationTests.java
package cn.saytime; import cn.saytime.domain.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootRedisApplicationTests { @Autowired private RedisTemplate<String, Object> redisTemplate; @Test public void contextLoads() { // 存取字符串 redisTemplate.opsForValue().set("a", "1"); Object a = redisTemplate.opsForValue().get("a"); System.out.println(a); // 存取user对象 redisTemplate.opsForValue().set("user1", new User(1, "张三")); User user1 = (User) redisTemplate.opsForValue().get("user1"); System.out.println(user1); } }
先开启redis服务,然后执行测试代码,输出结果为:
1 User{ id=1, name=张三}
测试redis成功
其他list,hash等方法这里就不演示了,具体查看api即可。
上一篇:
IDEA上Java项目控制台中文乱码