springboot2默认情况下使用lettuce框架访问redis
只需要在pom.xml文件添加以下依赖即可:
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-data-redis</artifactid>
</dependency>
<dependency>
<groupid>org.apache.commons</groupid>
<artifactid>commons-pool2</artifactid>
</dependency> 在需要访问redis的类中注入stringredistemplate实例
@autowired stringredistemplate stringredistemplate;
基本用法
// 获取hashoperations
hashoperations<string, string, string> hashoperations = stringredistemplate.opsforhash();
//add
hashoperations.put("user_hash","zhangfei","black face");
//update put会覆盖,相当于update
hashoperations.put("user_hash","zhangfei","mangfu");
//list 这里感觉叫list不好叫all吧
map<string, string> usermap = hashoperations.entries("user_hash"); // entries
set<string> userkeys = hashoperations.keys("user_hash");// keys
list<string> uservalues = hashoperations.values("user_hash"); // values
//delete
hashoperations.delete("user_hash","zhangfei3");
//是否存在
boolean aboolean = hashoperations.haskey("user_hash", "zhangfei"); // 是否存在
简化string操作方式
@controller
@requestmapping("hash")
public class hashcontroller {
@autowired
private stringredistemplate stringredistemplate;
@responsebody
@requestmapping("/add")
public map<string,string> add(){
hashoperations<string, string, string> hashoperations = stringredistemplate.opsforhash();
hashoperations.put("user_hash","zhangfei","black face"); // put相当于添加
hashoperations.put("user_hash","guanyu","red face");
return getall();
}
@responsebody
@requestmapping("/update")
public map<string,string> update(){
hashoperations<string, string, string> hashoperations = stringredistemplate.opsforhash();
boolean aboolean = hashoperations.haskey("user_hash", "zhangfei"); // 是否存在
system.out.println(aboolean);
hashoperations.put("user_hash","zhangfei","mangfu"); //put 会重置,相当于update
return getall();
}
@responsebody
@requestmapping("/all")
public map<string,string> all(){
return getall();
}
@responsebody
@requestmapping("/delete")
public map<string,string> delete(){
hashoperations<string, string, string> hashoperations = stringredistemplate.opsforhash();
hashoperations.delete("user_hash","zhangfei3");
return getall();
}
public map<string,string> getall(){
hashoperations<string, string, string> hashoperations = stringredistemplate.opsforhash();
map<string, string> usermap = hashoperations.entries("user_hash"); // entries
final set<string> userkeys = hashoperations.keys("user_hash"); // keys
list<string> uservalues = hashoperations.values("user_hash"); // values
return usermap;
}
}
string(字符串)
private void testvalue(){
valueoperations<string, string> value = stringredistemplate.opsforvalue();
value.getoperations().delete("aaa"); //删除
value.getoperations().delete("bbb");
value.set("aaa", "123"); //set
system.out.println(value.setifabsent("aaa", "123")); //没有才set
system.out.println(value.size("aaa")); //长度
system.out.println(value.get("aaa")); //获取值
value.append("aaa", "456"); //追加
system.out.println(value.get("aaa"));
value.increment("bbb", 1); //数值自增
system.out.println(value.get("bbb"));
value.multiget(arrays.aslist("aaa", "bbb", "ccc"))
.stream().foreach(system.out::println);
} hash(散列)
private void testhash(){
hashoperations<string, string, string> hash = stringredistemplate.opsforhash();
hash.getoperations().delete("hash1");
hash.put("hash1", "aaa", "111"); //put
hash.put("hash1", "bbb", "222");
hash.put("hash1", "ccc", "333");
system.out.println(hash.size("hash1")); //长度
hash.entries("hash1").foreach((k,v) -> { //显示所有的key和value
system.out.println(k + "=" + v);
});
hash.keys("hash1").stream().foreach(system.out::println); //显示所有的key
hash.values("hash1").stream().foreach(system.out::println); //显示所有的value
system.out.println(hash.putifabsent("hash1", "aaa", "aaa")); //没有key才put
hash.increment("hash1", "count", 1); //数值自增
system.out.println(hash.get("hash1", "count"));
hash.increment("hash1", "count", 1);
system.out.println(hash.get("hash1", "count"));
hash.increment("hash1", "count", -1);
system.out.println(hash.get("hash1", "count"));
system.out.println(hash.haskey("hash1", "amount")); //判断key是否存在
system.out.println(hash.get("hash1", "count"));
hash.delete("hash1", "count"); //删除
} set(集合)
private void testset(){
setoperations<string, string> set = stringredistemplate.opsforset();
set.getoperations().delete("set1");
set.getoperations().delete("set2");
set.add("set1", "111", "222", "333", "111");
set.add("set2", "222", "333", "444");
system.out.println(set.size("set1")); //长度
system.out.println(set.members("set1")); //获取所有值
system.out.println(set.members("set2"));
system.out.println(set.difference("set1", "set2")); //从前者取得与后者不一样的元素
system.out.println(set.intersect("set1", "set2")); //交集
system.out.println(set.union("set1", "set2")); //并集
set.remove("set1", "111"); //删除一个元素
system.out.println(set.pop("set1")); //弹出一个元素
system.out.println(set.randommember("set2")); //随机取一个元素
system.out.println(set.ismember("set2", "444")); //给定元素是否是成员
set.move("set2", "444", "set1"); //移动
system.out.println(set.members("set1"));
} list(列表)
private void testlist() {
listoperations<string, string> list = stringredistemplate.opsforlist();
list.getoperations().delete("list"); //清空
list.leftpush("list", "111"); //push 放到list中
list.leftpushifpresent("list", "222");
list.rightpush("list", "333");
list.rightpushifpresent("list", "444");
system.out.println(list.index("list", 0));
system.out.println(list.range("list", 0, -1));
list.trim("list", 0, 2); //截取
system.out.println(list.range("list", 0, -1));
system.out.println(list.leftpop("list")); //pop 取出消费掉
system.out.println(list.rightpop("list"));
} zset(有序集合)
private void testzset(){
zsetoperations<string, string> zset = stringredistemplate.opsforzset();
zset.getoperations().delete("zset1");
zset.getoperations().delete("zset2");
zset.add("zset1", "aaa", 1);
zset.add("zset1", "bbb", 1);
zset.add("zset1", "ccc", 1);
zset.add("zset2", "bbb", 1);
zset.add("zset2", "ccc", 1);
zset.add("zset2", "ddd", 1);
system.out.println(zset.size("zset1")); //长度
system.out.println(zset.range("zset1", 0, -1)); //取所有元素
zset.incrementscore("zset1", "bbb", 1); //增加分数score
zset.incrementscore("zset1", "aaa", 2);
system.out.println(zset.range("zset1", 0, -1)); //分数递增排序
zset.rangewithscores("zset1", 0, -1).stream().foreach(t -> {
system.out.println(t.getvalue() + "-" + t.getscore());
});
system.out.println(zset.reverserange("zset1", 0, -1)); //分数递减排序
zset.reverserangewithscores("zset1", 0, -1).stream().foreach(t -> {
system.out.println(t.getvalue() + "-" + t.getscore());
});
system.out.println(zset.rank("zset1", "ccc")); //分数递增排序,取元素的索引
system.out.println(zset.reverserank("zset1", "ccc")); //分数递减排序,取元素的索引
system.out.println(zset.score("zset1", "bbb")); //取元素的分数
zset.remove("zset2", "bbb"); //删除元素
system.out.println(zset.range("zset2", 0, -1));
} 登录案列
package com.cjs.example.controller;
import com.cjs.example.responseresult;
import com.cjs.example.domain.loginrequest;
import com.cjs.example.domain.loginresponse;
import com.cjs.example.domain.refreshrequest;
import com.cjs.example.enums.responsecodeenum;
import com.cjs.example.utils.jwtutil;
import org.apache.commons.lang3.stringutils;
import org.apache.tomcat.util.security.md5encoder;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.beans.factory.annotation.value;
import org.springframework.data.redis.core.hashoperations;
import org.springframework.data.redis.core.stringredistemplate;
import org.springframework.validation.bindingresult;
import org.springframework.validation.annotation.validated;
import org.springframework.web.bind.annotation.*;
import java.util.uuid;
import java.util.concurrent.timeunit;
@restcontroller
public class logincontroller {
/**
* apollo 或 nacos
*/
@value("${secretkey:123456}")
private string secretkey;
@autowired
private stringredistemplate stringredistemplate;
/**
* 登录
*/
@postmapping("/login")
public responseresult login(@requestbody @validated loginrequest request, bindingresult bindingresult) {
if (bindingresult.haserrors()) {
return responseresult.error(responsecodeenum.parameter_illegal.getcode(), responsecodeenum.parameter_illegal.getmessage());
}
string username = request.getusername();
string password = request.getpassword();
// 假设查询到用户id是01
string userid = "01";
if ("hello".equals(username) && "world".equals(password)) {
// 生成token
string token = jwtutil.generatetoken(userid, secretkey);
// 生成刷新token
string refreshtoken = uuid.randomuuid().tostring().replace("-", "");
// 放入缓存
hashoperations<string, string, string> hashoperations = stringredistemplate.opsforhash();
// hashoperations.put(refreshtoken, "token", token);
// hashoperations.put(refreshtoken, "user", username);
// stringredistemplate.expire(refreshtoken, jwtutil.token_expire_time, timeunit.milliseconds);
/**
* 如果可以允许用户退出后token如果在有效期内仍然可以使用的话,那么就不需要存redis
* 因为,token要跟用户做关联的话,就必须得每次都带一个用户标识,
* 那么校验token实际上就变成了校验token和用户标识的关联关系是否正确,且token是否有效
*/
// string key = md5encoder.encode(userid.getbytes());
string key = userid;
hashoperations.put(key, "token", token);
hashoperations.put(key, "refreshtoken", refreshtoken);
stringredistemplate.expire(key, jwtutil.token_expire_time, timeunit.milliseconds);
loginresponse loginresponse = new loginresponse();
loginresponse.settoken(token);
loginresponse.setrefreshtoken(refreshtoken);
loginresponse.setusername(userid);
return responseresult.success(loginresponse);
}
return responseresult.error(responsecodeenum.login_error.getcode(), responsecodeenum.login_error.getmessage());
}
/**
* 退出
*/
@getmapping("/logout")
public responseresult logout(@requestparam("userid") string userid) {
hashoperations<string, string, string> hashoperations = stringredistemplate.opsforhash();
string key = userid;
hashoperations.delete(key);
return responseresult.success();
}
/**
* 刷新token
*/
@postmapping("/refreshtoken")
public responseresult refreshtoken(@requestbody @validated refreshrequest request, bindingresult bindingresult) {
string userid = request.getuserid();
string refreshtoken = request.getrefreshtoken();
hashoperations<string, string, string> hashoperations = stringredistemplate.opsforhash();
string key = userid;
string originalrefreshtoken = hashoperations.get(key, "refreshtoken");
if (stringutils.isblank(originalrefreshtoken) || !originalrefreshtoken.equals(refreshtoken)) {
return responseresult.error(responsecodeenum.refresh_token_invalid.getcode(), responsecodeenum.refresh_token_invalid.getmessage());
}
// 生成新token
string newtoken = jwtutil.generatetoken(userid, secretkey);
hashoperations.put(key, "token", newtoken);
stringredistemplate.expire(userid, jwtutil.token_expire_time, timeunit.milliseconds);
return responseresult.success(newtoken);
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论