当前位置:网站首页>Redis single sign on system + voting system
Redis single sign on system + voting system
2022-06-26 18:26:00 【[email protected]】
Redis Single sign on System (SSO)
In distributed systems , There will be multiple services , After we log in to a service , When accessing other services , Don't want to log in again , You need a separate authentication system , We usually call it single sign on System , An authentication server is provided in this system , The service completes user authentication , In some small and medium-sized distributed systems , We usually use redis Store user authentication information , for example :

Key code implementation
package com.jt;
import redis.clients.jedis.Jedis;
import java.util.UUID;
/**
* be based on redis Design and implementation of single sign on
* 1) After the user logs in successfully, the login status and other information will be stored in redis
* 2) The user carries token Visit resources , The resource server should be based on token from redis Query user information
*/
public class SSODemo01 {
/**
* Perform login authentication , In the future, such services will be written to the authentication server
* @param username
* @param password
*/
static String doLogin(String username,String password){
//1. Check the validity of the data ( Determine the user name , Whether the password is empty , The length of the password , Whether there are special symbols of numbers and letters )
if(username==null||"".equals(username))
throw new IllegalArgumentException(" User cannot be empty ");
//2. Query user information based on user name , And determine whether the password is correct
if(!"jack".equals(username))
throw new RuntimeException(" This user does not exist ");
if(!"123456".equals(password))
throw new RuntimeException(" Incorrect password ");
//3. The user exists and the password is correct , Write user information to redis
Jedis jedis = JedisDataSource.getConnection();
String token= UUID.randomUUID().toString();
jedis.hset(token, "username", username);
jedis.hset(token, "permission", "sys:resource:create");
jedis.expire(token, 10);// Set up key Effective time of
jedis.close();
//4. take token Return to the client ( Future use response Object responds to the client ).
return token;
}
static String token;
/**
* Demonstrate the resource access process
* 1) Allow anonymous access ( No need to log in )
* 2) Access after login ( certified )
* 3) After logging in, you must have permission to access
*/
static Object doGetResource(String token){
//1. check token Is it empty
if(token==null)
throw new IllegalArgumentException(" Please log in first ");
//2. be based on token Inquire about redis data , If there is corresponding data, it indicates that the user has logged in
// Mode one Jedis jedis=new Jedis("192.168.126.128", 6379);
Jedis jedis = JedisDataSource.getConnection();
String username=jedis.hget(token, "username");
if(username==null)
throw new RuntimeException(" login timeout , Please login again ");
String permission=jedis.hget(token, "permission");
jedis.close();
//3. Check whether the user has access to the resource , If so, allow access to
if(!"sys:resource:create".equals(permission))
throw new RuntimeException(" You don't have access to this resource ");
//4. Returns the resource to access .
return " Resource access succeeded !";
}
public static void main(String[] args) {
//1. Login operation ( User authentication )
token=doLogin("jack", "123456");
System.out.println(token);
//2. carry token Access resource server
Object result=doGetResource(token);
System.out.println(result);
}
}
Simple voting system
In many systems design , There will be an activity design , Before starting an activity , We can conduct a survey on the support for this activity first , For example, design a voting system based on this activity , for example :

package com.jt;
import com.jt.JedisDataSource;
import redis.clients.jedis.Jedis;
import java.util.Set;
/**
* Design of a simple voting system based on an activity
* 1) The voting data is stored in redis (key For the event id, Multiple users id Set )
* 2) The same user cannot vote more than once
* 3) Specific business operations ( vote , Get the total number of votes , Check whether you have voted , Cancel the vote , Get who voted )
*/
public class VoteDemo01 {
/**
* Get a vote on who performed the event
* @param activityId
* @return
*/
static Set<String> doGetMembers(String activityId){
//1. Establishing a connection
Jedis jedis = JedisDataSource.getConnection();
//2. Get the total number of votes for the current activity
Set<String> smembers = jedis.smembers(activityId);
//3. Release resources
jedis.close();
return smembers;
}
/**
* Gets the total number of votes for the specified event
* @param activityId
* @return
*/
static Long doCount(String activityId){
//1. Establishing a connection
Jedis jedis = JedisDataSource.getConnection();
//2. Get the total number of votes for the current activity
Long count=jedis.scard(activityId);
//3. Release resources
jedis.close();
return count;
}
/**
* Execute voting operation
* @param activityId
* @param userId
*/
static void doVote(String activityId,String userId){
//1. Establishing a connection
Jedis jedis = JedisDataSource.getConnection();
//2. Executive voting
//2.1 Check whether you have voted
Boolean flag = jedis.sismember(activityId, userId);
//2.2 Execute a vote or cancel a vote
if(flag){
// If you have voted , Vote again and cancel the vote
jedis.srem(activityId, userId);
}else{
// If you have not cast a vote, you will vote
jedis.sadd(activityId, userId);
}
//3. Release resources
jedis.close();
}
public static void main(String[] args) {
String activityId="101";
String userId1="1";
String userId2="2";
String userId3="3";
// Execute voting action
doVote(activityId, userId1);
doVote(activityId, userId2);
doVote(activityId, userId3);
// Get the total number of votes
Long aLong = doCount(activityId);
System.out.println(" Total votes :"+aLong);
// Get the members who voted
Set<String> members= doGetMembers(activityId);
System.out.println(" Number of votes :"+members);
}
}
版权声明
本文为[[email protected]@yxg]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261820088337.html
边栏推荐
- Deep understanding of MySQL lock and transaction isolation level
- JS common regular expressions
- 知識點總結
- Temporarily turn off MySQL cache
- Runtimeerror: CUDA error: out of memory own solution (it is estimated that it is not applicable to most people in special circumstances)
- 临时关闭MySQL缓存
- 利用递归实现求n位所有格雷码
- 商品秒杀系统
- ROS的发布消息Publishers和订阅消息Subscribers
- Chinese (Simplified) language pack
猜你喜欢

IDEA收藏代码、快速打开favorites收藏窗口

爬取豆瓣读书Top250,导入sqlist数据库(或excel表格)中

tag动态规划-刷题预备知识-2. 0-1背包理论基础和二维数组解法模板

Let torch cuda. is_ Experience of available() changing from false to true

Paging query and join Association query optimization

idea中文插件chinese(simplified) language pack

Idea collection code, quickly open favorites collection window

零时科技 | 智能合约安全系列文章之反编译篇

ISO文件

VCD video disc
随机推荐
How pycharm modifies multiline annotation shortcuts
SSO微服务工程中用户行为日志的记录
Summary of alter operation in SQL
Résumé des points de connaissance
Interview key points that must be mastered index and affairs (with B-tree and b+ tree)
Handwritten numeral recognition based on tensorflow
几种常见的UML关系图汇总
GDB installation
System table SQLite of SQLite database_ master
带你解决哈希冲突,并实现一个简单hash表,
基于tensorflow的手写数字识别
50行代码爬取Top500图书导入TXT文档
物联网协议的王者:MQTT
xlua获取ugui的button注册click事件
输入n个整数,输出出现次数大于等于数组长度一半的数
成功解决之微服务@Value获取配置文件乱码问题
PC end records 515 ground sweeping robot /scan data
SQL中的并、交、差运算
Connected to surface test questions
How about opening a flush account? Is it safe? How to open a stock trading account