您的位置:首页 > 数据库 > Redis

Redis学习(3.1)spring boot整合Redis速成

2016-08-03 14:11 260 查看
本例子中,是最简略的spring boot使用redis的方式

一,pom.xml中添加

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


二,application.properties添加

spring.redis.database=0
spring.redis.host=200.200.200.177
spring.redis.password=foobared
spring.redis.pool.max-active=8
spring.redis.pool.max-idle=8
spring.redis.pool.max-wait=-1
spring.redis.pool.min-idle=0
spring.redis.port=6377
spring.redis.timeout=0


三,创建CachingConfigurerSupport 

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {}


四,使用redis

@Service
public class RedisService {
@Cacheable(value = "usercache")
public User getUser(String no,String name){
LogCore.BASE.debug("invoke persistent:{},{}", no, name);
return new User(no, name);
}
}


public class User implements Serializable {
private static final long serialVersionUID = 1L;
public String no;
public String name;

public User(String no, String name) {
this.no = no;
this.name = name;
}
}
@RestController
public class RedisController {
@Autowired
RedisService redisService;

@RequestMapping("/redis/test")
public Object test(String name, String no){
String _name = Objects.toString(name, "testName");
String _no = Objects.toString(no, "testNo");
return redisService.getUser(_no, _name);
}
}


启动后测试 http://localhost:8084/redis/test?name=tianyue&no=gao
返回结果

{"no":"gao","name":"tianyue"}

tips:

a.User要继承Serializable接口

b.没有指定redis的key的生成规则,则默认的规则为parms的简单链接,如本例子中name=tianyue&no=gao的key为gaotianyue,但是这样的话name=otianyue&no=ga也是gaotianyue,要自定义key方式,请看3.2下一篇文章
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: