您的位置:首页 > 编程语言 > Java开发

第三章 springboot + jedisCluster

2016-04-02 16:08 225 查看
如果使用的是redis2.x,在项目中使用客户端分片(Shard)机制。(具体使用方式:第九章 企业项目开发--分布式缓存Redis(1) 第十章 企业项目开发--分布式缓存Redis(2)

如果使用的是redis3.x中的集群,在项目中使用jedisCluster。

redis3.2.5集群搭建:第十二章 redis-cluster搭建(redis-3.2.5)

1、项目结构

package com.xxx.firstboot.web;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.xxx.firstboot.common.MyConstants;
import com.xxx.firstboot.domain.User;
import com.xxx.firstboot.redis.MyRedisTemplate;
import com.xxx.firstboot.service.UserService;

/**
* @RestController:spring mvc的注解,
* 相当于@Controller与@ResponseBody的合体,可以直接返回json
*/
@RestController
@RequestMapping("/user")
public class UserController {

@Autowired
private UserService userService;

@Autowired
private MyRedisTemplate myRedisTemplate;

@RequestMapping("/getUser")
public User getUser() {
return userService.getUser();
}

@RequestMapping("/testJedisCluster")
public User testJedisCluster(@RequestParam("username") String username){
String value =  myRedisTemplate.get(MyConstants.USER_FORWARD_CACHE_PREFIX, username);
if(StringUtils.isBlank(value)){
myRedisTemplate.set(MyConstants.USER_FORWARD_CACHE_PREFIX, username, JSON.toJSONString(getUser()));
return null;
}
return JSON.parseObject(value, User.class);
}

}


View Code

说明:相对于上一章,只是添加了测试缓存的方法testJedisCluster。

测试:

在Application.properties右击-->run as-->java application,在浏览器输入"localhost:8080/user/testJedisCluster?username=xxx"即可。

附:对于redis的测试,我们有时需要查看执行set后,缓存是否存入redis的db中了,有两种方式

执行set后,get数据,之后修改数据,在get数据,比较两次get的数据是否相同即可

有时,这些数据是无法修改的(假设该数据是我们从第三方接口得来的),这个时候可以使用redis-desktop-manager这个软件来查看缓存是否存入redis(该软件的使用比较简单,查看官网)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: