当前位置:网站首页>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
边栏推荐
猜你喜欢

In and exceptions, count (*) query optimization

ARM裸板调试之串口打印及栈初步分析

9. Intelligent transportation project (2)

Image binarization

xlua获取ugui的button注册click事件

SSO微服务工程中用户行为日志的记录

Row lock analysis and deadlock

Solve the problem that each letter occupies a space in pycharm

带你解决哈希冲突,并实现一个简单hash表,

Clion breakpoint single step debugging
随机推荐
ISO documents
CLion断点单步调试
Redis单点登陆系统+投票系统
Temporarily turn off MySQL cache
sql中的几种删除操作
wm_ Concat() and group_ Concat() function
Comparing the size relationship between two objects turns out to be so fancy
wm_concat()和group_concat()函数
In and exceptions, count (*) query optimization
MYSQL的下载与配置 mysql远程操控
Publish message publishers and subscribe message subscribers of ROS
[unity] use C in unity to execute external files, such as Exe or bat
Handwritten promise all
The eigen library calculates the angle between two vectors
Yujun product methodology
Tag dynamic programming - preliminary knowledge for question brushing -2 0-1 knapsack theory foundation and two-dimensional array solution template
vuex中利用缓存解决刷新state数据丢失问题
DAPP丨LP单双币流动性质押挖矿系统开发原理分析及源码
Case study of row lock and isolation level
读书笔记:《过程咨询 III》